# coreBugZJ

## 你的编程语言能这样做吗 （转）

```    // 一个小例子：

```    function SwedishChef( food )
{
alert("I'd like some " + food + "!");
}

SwedishChef("Spaghetti");
SwedishChef("Chocolate Moose");```

```    alert("get the lobster");
PutInPot("lobster");
PutInPot("water");

BoomBoom("chicken");
BoomBoom("coconut");```

```    function Cook( i1, i2, f )
{
f(i1);
f(i2);
}

Cook( "lobster", "water", PutInPot );
Cook( "chicken", "coconut", BoomBoom );```

```    Cook( "lobster",
"water",
function(x) { alert("pot " + x); }  );
Cook( "chicken",
"coconut",
function(x) { alert("boom " + x); } );```

```    var a = [1,2,3];

for (i=0; i<a.length; i++)
{
a[i] = a[i] * 2;
}

for (i=0; i<a.length; i++)
{
}```

```    function map(fn, a)
{
for (i = 0; i < a.length; i++)
{
a[i] = fn(a[i]);
}
}```

```    map( function(x){return x*2;}, a );

```    function sum(a)
{
var s = 0;
for (i = 0; i < a.length; i++)
s += a[i];
return s;
}

function join(a)
{
var s = "";
for (i = 0; i < a.length; i++)
s += a[i];
return s;
}

sumjoin 看起来非常的相似，你也许会想把它们的通用之处提取出来做成一个能把数组里的元素合并成一个值的通用函数：

```    function reduce(fn, a, init)
{
var s = init;
for (i = 0; i < a.length; i++)
s = fn( s, a[i] );
return s;
}

function sum(a)
{
return reduce( function(a, b){ return a + b; },
a, 0 );
}

function join(a)
{
return reduce( function(a, b){ return a + b; },
a, "" );
}```

posted on 2012-04-12 16:30 coreBugZJ 阅读(2063) 评论(5)  编辑 收藏 引用 所属分类: 技术视野SoftwareProgrammingLanguageLisp

### Feedback

#### #re: 你的编程语言能这样做吗 （转） 2012-04-12 20:25 lltg

C语言虽然有函数，但是C语言不支持闭包。

struct cl {
void* func;
void* paramters[0];
}