Skip to content

Instantly share code, notes, and snippets.

@brendanberg
Created August 24, 2011 07:11
Show Gist options
  • Save brendanberg/1167460 to your computer and use it in GitHub Desktop.
Save brendanberg/1167460 to your computer and use it in GitHub Desktop.
Lisp list functions in CoffeeScript
cons = (h, t) -> (m) -> m(h, t)
car = (x) -> x((h, t) -> h)
cdr = (x) -> if x then x((h, t) -> t) else null
map = (ls, f) ->
cons (f car ls), if cdr ls then map cdr(ls), f else null
foldl = (ls, f, n) ->
f (car ls), if cdr ls then foldl (cdr ls), f, n else n
foldr = (ls, f, n) ->
f (if cdr ls then foldr (cdr ls), f, n else n), car ls
filter = (ls, fn) ->
if fn car ls
cons (car ls), if cdr ls then filter (cdr ls), fn else null
else
filter (cdr ls), fn
append = (ls1, ls2) ->
if ls1 == null
ls2
else
cons (car ls1), append (cdr ls1), ls2
length = (ls, n=0) ->
if ls == null
n
else
length (cdr ls), n + 1
index = (l, i) ->
if i == 0
car l
else
index (cdr l), i - 1
a = cons 1, cons 2, cons 3, cons 4, null
b = cons 5, cons 6, cons 7, cons 8, null
z = append a, b
y = map z, (x) -> x * x
x = filter z, (x) -> x > 2
tostring = (l) -> foldl l, ((x, y) -> String(x) + ',' + String(y)), "nil"
alert (tostring z) + ' has length ' + (length z)
alert 'The 4th element of ' + (tostring y) + ' is ' + (index y, 3)
alert tostring x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment