-
-
Save julietr/452ec47ccd68771f9b0d to your computer and use it in GitHub Desktop.
Ruby != Lisp
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 cons(x, xs) | |
lambda { |f| f.call(x, xs) } | |
end | |
def car(f) | |
f.call(lambda { |x, xs| x }) | |
end | |
def cdr(f) | |
f.call(lambda { |x, xs| xs }) | |
end | |
def fold(xs, seed, f) | |
while xs != nil do | |
seed = f.call(seed, car(xs)) | |
xs = cdr(xs) | |
end | |
seed | |
end | |
def rev(xs) | |
fold(xs, nil, lambda { |xs, x| cons(x, xs)}) | |
end | |
def map(xs, f) | |
rev(fold(xs, nil, lambda { |xs, x| cons(f.call(x), xs)})) | |
end | |
def filter(xs, f) | |
rev(fold(xs, nil, lambda { |xs, x| if f.call(x) then cons(x, xs) else xs end })) | |
end | |
def iter(xs, f) | |
fold(xs, nil, lambda { |_, x| f.call(x) }) | |
end | |
def append(xs, ys) | |
if xs == nil then ys | |
elsif ys == nil then xs | |
else cons(car(xs), append(cdr(xs), ys)) | |
end | |
end | |
def print_list(xs) | |
iter(xs, lambda { |x| puts x }) | |
end | |
def debug(xs) | |
print_list xs | |
xs | |
end | |
a = debug(cons(1, cons(2, cons(3, nil)))) | |
sum = fold(a, 0, lambda { |a, b| a + b }) | |
b = debug(map(a, lambda { |x| x * 5 })) | |
c = debug(filter(b, lambda { |x| x <= 10 })) | |
d = debug(append(append(a, b),c)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment