Skip to content

Instantly share code, notes, and snippets.

@ongaeshi
Created February 6, 2017 16:24
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 ongaeshi/69bd66cb545dda12aa1cb57f63076354 to your computer and use it in GitHub Desktop.
Save ongaeshi/69bd66cb545dda12aa1cb57f63076354 to your computer and use it in GitHub Desktop.
def _eval(exp)
if not list?(exp)
if immediate_val?(exp)
exp
else
lookup_primitive_fun(exp)
end
else
fun = _eval(car(exp))
args = eval_list(cdr(exp))
apply(fun, args)
end
end
def list?(exp)
exp.is_a? Array
end
def lookup_primitive_fun(exp)
$primitive_fun_env[exp]
end
$primitive_fun_env = {
:+ => [:prim, lambda{|x,y| x + y }],
:- => [:prim, lambda{|x,y| x - y }],
:* => [:prim, lambda{|x,y| x * y }],
}
def car(list)
list[0]
end
def cdr(list)
list[1..-1]
end
def eval_list(exp)
exp.map {|e| _eval(e)}
end
def immediate_val?(exp)
num?(exp)
end
def num?(exp)
exp.is_a? Numeric
end
def apply(fun, args)
apply_primitive_fun(fun, args)
end
def apply_primitive_fun(fun, args)
fun_val = fun[1]
fun_val.call(*args)
end
# puts _eval([:+, 1, 2])
puts _eval([:+, [:+, 1, 2], 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment