public
Created — forked from bkyrlach/AST.cs

Lambda for Scala...

  • Download Gist
Lambda.scala
Scala
1 2 3 4 5 6 7 8 9 10 11
object Lambda extends App {
val number = (num: Int) => (env: Map[Symbol, Int]) => num
val variable = (id: Symbol) => (env: Map[Symbol, Int]) => env(id)
val add = (a: (Map[Symbol, Int]) => Int, b: (Map[Symbol, Int]) => Int ) => (env: Map[Symbol, Int]) => a(env) + b(env)
val multiply = (a: (Map[Symbol, Int]) => Int, b: (Map[Symbol, Int]) => Int ) => (env: Map[Symbol, Int]) => a(env) * b(env)
val environment = Map('a -> 1, 'b -> 2, 'c -> 3)
val expr_tree = add(variable('a), multiply(number(2), variable('b)))
 
println(expr_tree(environment))
}
Lamda2.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Expr(f: Function1[Map[Symbol,Int], Int]) {
def apply(env: Map[Symbol, Int]): Int = f(env)
}
 
object Lambda extends App {
val number: Int => Expr = num => new Expr(env => num)
val variable = (id: Symbol) => new Expr(env => env(id))
val add = (a: Expr, b: Expr) =>new Expr(env => a(env) + b(env))
val multiply = (a: Expr, b: Expr ) => new Expr(env => a(env) * b(env))
val environment = Map('a -> 1, 'b -> 2, 'c -> 3)
val expr_tree = add(variable('a), multiply(number(2), variable('b)))
println(expr_tree(environment))
}
cool.clj
Clojure
1 2 3 4 5 6 7 8 9
(defn number [n] #(do % n))
(defn variable [x] #(% x))
(defn add [f1 f2] #(+ (f1 %) (f2 %))
(defn multiply [f1 f2] #(* (f1 %) (f2 %))
 
(def environment {:a 3, :b 4, :c 5})
(def expression-tree (add (variable :a) (multiply (number 2) (variable a)))
 
(expression-tree environment)
test.rb
Ruby
1 2 3 4 5 6 7 8 9
def Number(num) lambda { |env| num } end
def Variable(var) lambda {|env| env[var] } end
def Add(f1, f2) lambda {|env| f1(env)+f2(env) } end
def Multiply(f1, f2) lambda {|env| f1(env)*f2(env) } end
 
ExpressionTree = Add(Variable(:a),Multiply(Number(2), Variable(:b)))
Env = { a: 3, b: 4, c: 5 }
 
puts ExpressionTree(Env)

Fixed the test.rb example.

def Number(num)      ->(env){ num } end
def Variable(var)    ->(env){ env[var] } end
def Add(f1, f2)      ->(env){ f1.(env)+f2.(env) } end
def Multiply(f1, f2) ->(env){ f1.(env)*f2.(env) } end

ExpressionTree = Add(Variable(:a), Multiply(Number(2), Variable(:b)))
Env = { a: 3, b: 4, c: 5 }

p ExpressionTree.(Env)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.