国庆7天容易无聊,于是我打算实现一下以前失败过的一种语言的特性:类型推导。于是顺便做一做惰性计算吧。于是我尝试设计了一门特性尽可能少的语言,并且强制让一个函数的返回值仅跟输入的参数有关。虽然这个特性不适合用来做IO,但是是有办法解决的,而且不需要修改语言就可以直接支持。
这门语言的定义及其简单:
1 type TYPE P1 P2..=CTOR T1 T2 | TYPE |
2
3 func FUNC::TYPE
4 def FUNC P1 P2 = exp
5
6
7 unit=name
8 unit=value
9 unit=(name->exp)
10 exp=unit
11 exp=exp unit
12 exp=let DECLARATIONS in exp
13 exp=select exp of
14 case value : exp
15 case name : exp
16 case CTOR name/value : exp
17 else : exp
18 end
需要预先定义的部分也是很少的:
1 type int;
2 type char;
3 type bool = true | false
4 type list T = empty
5 | list T (list T)
6
7 func iadd::int->int->int call "add"
8 func isub::int->int->int call "sub"
9 func imul::int->int->int call "mul"
10 func idiv::int->int->int call "div"
11 func imod::int->int->int call "mod"
12 func ilg::int->int->bool call "ilg"
13 func ism::int->int->bool call "ism"
14 func iequ::int->int->bool call "iequ"
15 func chr::int->char call "chr"
16 func ord::char->int call "ord
于是我尝试实现了if、逻辑运算符以及itoa和atoi两个函数:
1 func not::bool->bool
2 def not a = select a of
3 true : false
4 false : true
5 end
6
7 func and::bool->bool->bool
8 def and a b = select a of
9 case true : b
10 case false : false
11 end
12
13 func or::bool->bool->bool
14 def aor a b = select a of
15 case true : true
16 case false : b
17 end
18
19 func xor::bool->bool->bool
20 def xor a b = select a of
21 case true : not b
22 case false : b
23 end
24
25 func T if::bool->T->T
26 def if cond t f = select cond of
27 case true : t
28 case false : f
29 end
30
31 func ineg::int->int
32 def ineg num = isub 0 num
33
34 func coffset::char->int->char
35 def coffset c i = chr (iadd (ord c) i)
36
37 func itoa::int->list char
38 def itoa a = if (iequ a 0) (list '0' empty) (if (ism a 0)
39 (list '-' (itoa (ineg a)))
40 let
41 func _itoa::int->(list char)->(list char)
42 def _itoa a chs = select a of
43 case 0 : chs
44 case else : _itoa (div a 10) (list (coffset '0' (mod a 10)) chs)
45 end
46 in _itoa a empty)
47
48 func atoi::list char->int
49 def atoi chs = select chs of
50 case empty : 0
51 case list '-' chs : ineg (atoi chs)
52 case c chs : iadd (imul 10 (isub (ord c) (ord '0'))) (atoi chs)
53 end
当然,语法绝大部分抄了haskell和LISP,因为实在不想再重新设计了,反正到头来差不多也是这个样子的。7天应该能做完它。
posted on 2008-09-28 07:14
陈梓瀚(vczh) 阅读(2140)
评论(4) 编辑 收藏 引用 所属分类:
脚本技术