Skip to content

Instantly share code, notes, and snippets.

@peas
Created June 13, 2011 03:58
Show Gist options
  • Save peas/1022295 to your computer and use it in GitHub Desktop.
Save peas/1022295 to your computer and use it in GitHub Desktop.
prog funcional em js. wip
<script type="text/javascript">
console.log("ola mundo");
function par(a, b) {
return function(f) {
return f(a, b);
}
}
function head(l) {
return l(function(a, b) {return a;});
}
function tail(l) {
return l(function(a, b) {return b;});
}
console.log(head(par(1,2)));
console.log(tail(par(1,2)));
function foreach(l, f) {
f(head(l));
if(tail(l) == null) return;
foreach(tail(l), f);
}
foreach(par(0, par(1, par(2, null))), function(x) {console.log(x);});
function lista(a) {
if(a.length == 0) return null;
return par(a[0], lista(a.slice(1)));
}
var x = lista([0,1,2,3,4,5]);
foreach(x, function(x) {console.log(x);});
function converte(l) {
if(tail(l) == null) return [head(l)];
return [head(l)].concat(converte(tail(l)));
}
function map(l, f) {
if(l == null) return null;
return par(f(head(l)), map(tail(l), f));
}
var y = map(x, function(x) {return x*2;});
console.log(converte(y));
function filter(l, f) {
if(l == null) return null;
return f(head(l)) ? par(head(l), filter(tail(l), f)) :
filter(tail(l), f);
}
var z = filter(y, function(x) {return x%4==0;});
console.log(converte(z));
function fold(l, i, op) {
if(l == null) return i;
return op(head(l), fold(tail(l), i, op));
}
function foldl(l, i, op) {
if(l == null) return i;
return foldl(tail(l), op(i, head(l)), op);
}
var zz = foldl(x, 0, function(a,b) {console.log(a,b); return a+b;});
console.log(zz);
function map2(l, f) {
return fold(l, null,
function(a, b) {
return par(f(a), b);}
);
}
function count(l, f) {
return fold(l, 0,
function(a, b) {
return f(a) ? b+1 : b;
});
}
var yy = map2(x, function(x) {return x*2;});
console.log(converte(yy));
console.log(count(yy, function(x) {return x%4==0;}));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment