函数式编程(javascirpt)
2010-09-14 13:44:24 来源:WEB开发网高阶函数提供了更高级的抽象,从而使得程序的结构更加清晰。下面我们再看看函数式语言的优雅的代码,匿名函数:
匿名函数
我们先对一些简单的操作进行简单的包装(如四则运算,boolean运算等操作):
function abs(x){ return x>0?x:-x;}
function add(a, b){ return a+b; }
function sub(a, b){ return a-b; }
function mul(a, b){ return a*b; }
function div(a, b){ return a/b; }
function rem(a, b){ return a%b; }
function inc(x){ return x + 1; }
function dec(x){ return x - 1; }
function equal(a, b){ return a==b; }
function great(a, b){ return a>b; }
function less(a, b){ return a<b; }
function negative(x){ return x<0; }
function positive(x){ return x>0; }
然后,在这些共用的语法糖(并非严格意义上的语法糖,但是它们的确是!)的基础上,做一些简单的函数定义:
// n*(n-1)*(n-2)*...*3*2*1
function factorial(n){
if(equal(n, 1)){
return 1;
}else{
return mul(n, factorial(dec(n)));
}
}
//对上边的函数的另一种定义方式
/*
* product <- counter * product
* counter <- counter + 1
* */
function factorial(n){
function fact_iter(product, counter, max){
if(counter > max){
return product;
}else{
fact_iter(mul(counter, product), inc(counter), max);
}
}
return fact_iter(1, 1, n);
}
function expt(b, n){
if(n == 0){
return 1;
}else{
return mul(expt(b, dec(n)), b);
}
}
function gcd(a, b){
if(b == 0){
return a;
}else{
return gcd(b, rem(a, b));
}
}
function search(fx, neg, pos){
function closeEnough(x, y){return less( abs( sub(x, y) ), 0.001)};
var mid = (function(x, y){return div( add(x, y), 2);})(neg, pos);
if(closeEnough(neg, pos)){
return mid;
}else{
var test = fx(mid);
if(positive(test)){
return search(fx, neg, mid);
}else if(negative(test)){
return search(fx, mid, pos);
}else{
return mid;
}
}
}
function halfIntervalMethod(fx, a, b){
var av = fx(a);
var bv = fx(b);
if(negative(av) && positive(bv)){
return search(fx, a, b);
}else if(negative(bv) && positive(av)){
return search(fx, b, a);
}else{
print("error happend!!");
}
}
//计算一个函数的不动点
function fixedPoint(fx, first){
var tolerance = 0.00001;
function closeEnough(x, y){return less( abs( sub(x, y) ), tolerance)};
function Try(guess){
var next = fx(guess);
//print(next+" "+guess);
if(closeEnough(guess, next)){
return next;
}else{
return Try(next);
}
};
return Try(first);
}
// magic function sqrt, a little hard to read, hah?
function sqrt(x){
return fixedPoint(
function(y){
return function(a, b){ return div(add(a, b), 2);}(y, div(x, y));
},
1.0);
}
Tags:函数 编程 javascirpt
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接