cse341_pl_partA_note_03
- Tuples and lists
- build up data with multiple parts
- 元组是固定数量的不同类型数据集合,列表是不定数量的相同类型集合。其实这么定义就是为了更好的在内存里管理空间
- pairs: 2-tuples
- sytanx: (e1, e2)
- evaluation: e1->v1, e2->v2, then (v1, v2)
- type-checking: e1->t1, e2->t2, then t1*t2
- how to acess :
- sytanx: #1 e and #2 e // record的语法糖
- evaluation and type-checking 和之前差不多
fun swap( pr : int * bool) = (#2 pr , #1 pr)
- tuples: (e1, e2, e3,......,en), type: (t1*t2*.....*tn), access: #1 e, #2 e,....,#n e, nested by what you want
- lists:
- build: empty [], more general [e1, e2,....]
- access: null xs -> true only if xs is [], null 只是一个pattern match,可以自己写一个的。还有两个函数 hd和tl,hd求出list第一个元素,tl为剩余的列表
fun sum_list(xs: int list) = if null xs then 0 else hd(xs) + sum_list( tl xs) fun append (xs: int list , ys: int list) = if null xs then yes else hd(xs) :: append(tl(xs) , ys)
- recursion: functions over lists are usually recursive- only way to get to the all the elements
- Local Bindings:
- syntax: let b1 b2...bn in e end
- type-checking: check b1-bn in a static environment that includes the previous bindings
- evaluation: evaluate b1-bn and e in a dynamic environment that includes the previous bindings.
- let-expression is just an expression
-
fun countup_from1 (x: int) = let fun count (from : int)= if from = x then x::[] else from :: count (from+1) in count 1 end
- avoid repeated recursion
-
fun max( xs: int list) = if null xs then 0 else if null (tl xs) then hd xs else let val tl_ans = max( tl xs) in if h xs > tl_ans then hd_xs else tl_ans end
options: t option is a type for any type t (much like t list, but a different type , not a list) //至今没太懂这个有什么意义
- building: NONE has 'a option ( much like [] has type 'a list)
- SOME e has type t option if e has type t
- access: isSome 'a option-> bool . valOf 'a option-> 'a
-
fun better_max ( xs: int list)= if null xs then NONE else let val tl_ans= better_max( tl xs ) in if isSome tl_ans andalso valOf tl_ans > hd xs then tl_ans else SOME (hd xs) end