Last active
January 3, 2016 00:09
-
-
Save XuefengWu/8381135 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
function head(l) { return l[0];} | |
function tail(l) { return l.slice(1, l.length);} | |
function map(f,l) { if(l.length ==0 ) {return l;} | |
else {return [f(head(l))].concat(map(f,tail(l)));}} | |
map(function (i) {return i+1}, [1,2,3]) //[2,3,4] | |
function filter(p,l) { | |
if(l.length == 0) {return l} | |
else { | |
if(p(head(l))) {return [head(l)].concat(filter(p,tail(l)));} | |
else {return filter(p,tail(l));} | |
} | |
} | |
filter(function(x) {return x > 0},[0,-1,2,3,4]) //[2,3,4] | |
function foldr(f,v,l) { | |
if(l.length == 0) {return v;} | |
else{ | |
return foldr(f,f(v,head(l)),tail(l)); | |
} | |
} | |
foldr(function(x,y){return x+y;},0,[1,2,3]) //6 | |
function reverse(l) { | |
if(l.length == 0) return l; | |
else { return reverse(tail(l)).concat(head(l));} } | |
function reverse2(l) { | |
return foldr(function(acc,e) {return [e].concat(acc);},[],l); | |
} | |
reverse2([1,2,3]) //[3,2,1] | |
function map2(f,l) { | |
return foldr(function(acc, e) {return acc.concat(f(e))}, [] , l); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment