Girish
unread,Nov 28, 2007, 5:49:24 AM11/28/07Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Principles of Programming with JavaScript
//compose :[isFunction,isFunction] ->isFunction
//compose function composes 2 functions
compose = function(f, g){
return (function(x){
return f(g(x))
});
}
/*Example:compose
*
* a = function(x){
* return x + 2;
* }
*
*
* b = function(x){
* return x + 1;
* }
*
* compose(a,b)(0) => 3
*
*/
//identity :[JSobj]->JSobj
//identity function
identity = function(x){
return x
}
//iterate : [isFunction,isNumber] -> isFunction
//iterate takes a function and iterates it n times
function iterate(f, n){
if (n == 0) {
return identity;
}
else {
for (i = 0; i < (n - 1); i++) {
f = compose(f, f);
}
return f;
}
}
/*Example :iterate
*
* foo=function(z){return z+1};
* iterate(foo,2)(0) ->2
*
*/
//another implementation of iterator without currying
//iter :[isFunction,isNumber,isNumber]->isNumber
function iter(f, n, x){
if (n == 0) {
return x;
}
else {
for (i = 0; i < n; i++) {
x = f(x);
}
return x;
}
}