Skip to content

Instantly share code, notes, and snippets.

@bkyrlach
Created June 18, 2012 16:00
Show Gist options
  • Save bkyrlach/2949105 to your computer and use it in GitHub Desktop.
Save bkyrlach/2949105 to your computer and use it in GitHub Desktop.
A more functional approach...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AST
{
class Program
{
static void Main(string[] args)
{
Func<int, Expr> number = (num => new Expr(env => num));
Func<string, Expr> variable = (id => new Expr(env => env[id]));
Func<Expr, Expr, Expr> add = ((a, b) => new Expr(env => a.apply(env) + b.apply(env)));
Func<Expr, Expr, Expr> multiply = ((a, b) => new Expr(env => a.apply(env) * b.apply(env)));
IDictionary<string, int> environment = new Dictionary<string, int>();
environment["a"] = 1;
environment["b"] = 2;
environment["c"] = 3;
Expr expr_tree = add(variable("a"), multiply(number(2), variable("b")));
Console.WriteLine(expr_tree.apply(environment));
}
}
class Expr
{
private Func<IDictionary<string, int>, int> f;
public Expr(Func<IDictionary<string, int>, int> f)
{
this.f = f;
}
public int apply(IDictionary<string, int> env)
{
return f(env);
}
}
}
object Lambda extends App {
val evaluate = (env: Map[Symbol, Int], f: (Map[Symbol, Int]) => Int) => f(env)
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]) => evaluate(env, a) + evaluate(env, b)
val multiply = (a: (Map[Symbol, Int]) => Int, b: (Map[Symbol, Int]) => Int ) => (env: Map[Symbol, Int]) => evaluate(env, a) + evaluate(env, b)
val environment = Map('a -> 1, 'b -> 2, 'c -> 3)
val expr_tree = add(variable('a), multiply(number(2), variable('b)))
println(evaluate(environment, expr_tree))
}
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))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment