Skip to content

Instantly share code, notes, and snippets.

@ckirkendall
Forked from bkyrlach/AST.cs
Created June 18, 2012 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckirkendall/2949141 to your computer and use it in GitHub Desktop.
Save ckirkendall/2949141 to your computer and use it in GitHub Desktop.
Lambda for Scala...
(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)
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))
}
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))
}
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)
@pmarreck
Copy link

pmarreck commented Sep 4, 2012

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment