"Implemenation of iterator in Javascript"

30 views
Skip to first unread message

Girish

unread,
Nov 28, 2007, 5:49:24 AM11/28/07
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;
}
}

Reply all
Reply to author
Forward
0 new messages