网络编程
位置:首页>> 网络编程>> JavaScript>> 极致之美——百行代码实现全新智能语言Lisp(4)

极致之美——百行代码实现全新智能语言Lisp(4)

作者:月影 来源:51js 发布时间:2010-07-13 13:07:00 

标签:Lisp,javascript

到这里为止我们很高兴地看到LispScript已经可以不依赖于javascript来扩展了

现在我们可以直接用LispScript定义一些新函数了:

函数:[isNull,x]测试它的自变量是否是空表.

LispScript.Run(
 [defun,'isNull',['x'],
  [eq,'x',[_,NIL]]]
);

> [isNull,[_,a]]
[]
> [isNull. [_,[]]]
t

函数:[and,x,y]返回t如果它的两个自变量都是t, 否则返回[].

LispScript.Run(
 [defun,'and',['x','y'],
  [cond,['x',[cond,['y',true],[true,NIL]],
   [true,NIL]]]]
);

> [and,[atom,[_,a]],[eq,[_,a],[_,a]]]
t
> [and,[atom,[_,a]],[eq,[_,a],[_,b]]]
[]

函数:[not,x]返回t如果它的自变量返回[],返回[]如果它的自变量返回t.

LispScript.Run(
 [defun,'append',['x','y'],
  [cond,[[isNull,'x'],'y'],
    [true,[cons,[car,'x'],['append',[cdr,'x'],'y']]]]]
);

> [append,[_,[a,b]],[_,[c,d]]]
[a,b,c,d]
> [append,[], [_,[c,d]]]
[c,d]

函数:[pair,x,y]取两个相同长度的表,返回一个由双元素表构成的表,双元素表是相应位置的x,y的元素对.

LispScript.Run(
 [defun,'pair',['x','y'],
  [cond,
   [[and,[isNull,'x'],[isNull,'y']],NIL],
   [[and,[not,[atom,'x']],[not,[atom,'y']]],
    [append,[[[car,'x'],[car,'y']]],['pair',[cdr,'x'],[cdr,'y']]]
   ]]]
);

> [pair,[_,[x,y,z]],[_,[a,b,c]]]
[[x,a],[y,b],[z,c]]

[assoc,x,y]取原子x和形如pair函数所返回的表y,返回y中第一个符合如下条件的表的第二个元素:它的第一个元素是x.

LispScript.Run(
 [defun,'assoc',['x','y'],
  [cond,[[eq,[car,[car,'y']],'x'],[car,[cdr,[car,'y']]]],
   [[isNull,'y'],NIL],[true,['assoc','x',[cdr,'y']]]]]
);

> [assoc,[_,x],[_,[[x,a],[y,b]]]]
a
> [assoc,[_,x],[_,[[x,new],[x,a],[y,b]]]]
new

[ret,e]返回表达式计算结果

LispScript.Run(
 [defun,'ret',['e'],[car,['e']]]
);

[str,e]返回表达式计算结果的引用

LispScript.Run(
 [defun,'str',['e'],[_,[_,'e']]]
);

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com