Skip to content

Instantly share code, notes, and snippets.

@tcql
Created February 12, 2012 05:10
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 tcql/1806486 to your computer and use it in GitHub Desktop.
Save tcql/1806486 to your computer and use it in GitHub Desktop.
Making CoffeeScript more Haskell-y
## The more functional way
head = (x) -> ((z,zs...) -> z) x...
tail = (x) -> ((z,zs...) -> zs) x...
last = (x) -> ((zs...,z) -> z) x...
init = (x) -> ((zs...,z) -> zs) x...
## OR, the more coffee-scripty way:
headCS = (xs) -> xs[0]
tailCS = (xs) -> xs[1..xs.length]
initCS = (xs) -> xs[0...xs.length-1]
lastCS = (xs) -> xs[xs.length-1]
reverse = (xs) -> foldl ((acc,x) -> [x].concat acc ),[],xs
## Folds, maps, filters
foldl = (fn,acc,xs) ->
acc = fn(acc,z) for z in xs
acc
foldr = (fn,acc,xs) ->
ls = reverse xs
acc = fn(z,acc) for z in ls
acc
map = (fn,xs) -> fn(x) for x in xs
filter = (pred,xs) -> x for x in xs when pred(x) is true
# Testing
foldSum = foldl ((acc,x) -> acc+x),0,[0..10]
filterGT5 = filter ((x) -> x > 5),[0..10]
mapX5 = map ((x) -> x*5),[0..10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment