Created
February 6, 2017 16:24
-
-
Save ongaeshi/69bd66cb545dda12aa1cb57f63076354 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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