Skip to content

Instantly share code, notes, and snippets.

@XuefengWu
Last active January 3, 2016 00:09
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 XuefengWu/8381135 to your computer and use it in GitHub Desktop.
Save XuefengWu/8381135 to your computer and use it in GitHub Desktop.
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