Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

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
Something went wrong with that request. Please try again.