Created
February 12, 2012 05:10
-
-
Save tcql/1806486 to your computer and use it in GitHub Desktop.
Making CoffeeScript more Haskell-y
This file contains hidden or 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
## 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