如下图所示,在ML语言中使用datatype关键字来构建one of types数据结构。下图指代的是,将int和string类型混杂在一起的数据结构。通过case expression来进行match pattern,然后进行计算。需要注意的是,case expression种很重要的就是将list拆成头和剩余部分,即x::xs'。
datatype int_or_string = I of int | S of string
fun funny_sum xs =
case xs of
[] => 0
| (I i)::xs' => i + funny_sum xs'
| (S s)::xs' => String.size s + funny_sum xs'
接下来提到的是递归的数据结构,如下所示:
datatype exp = Const of int
| Negate of exp
| Add of exp * exp
|Multiply of exp * exp
fun eval e =
case e of
Const i => i
| Negate e1 => ~(eval e1)
|Add(e1, e2) => (eval e1) + (eval e2)
|Multiply(e1, e2) => (eval e1) * (eval e2)
问题:为什么要将返回值为int修改为exp呢?即exp->exp,而不是exp->int
this way is more painful here, but takes much more sense for larger languages where recursive calls can return different kinds of
如下图所示,定义了内嵌函数(本质上和定义两个函数差不多,只是内嵌函数更加隐蔽)
So here's a function Const, just a plain old Racket function, takes in an argument i and returns a list with two elements, the single Const and then i.
For now just think of symbols as strings. I'll briefly mention at the end of this segment that they're not quite strings. But just think of them as strings.
问题:为什么要进行递归调用?