编程语言 :ML
参考:https://www.cnblogs.com/whensean/p/6134063.html
http://www.cnblogs.com/ftae/p/8039291.html
WEEK2:
例子:
//输出x到y之间所有的数的list
fun append (x: int, y: int) =
if y - x <0
then []
else x::append(x+1,y)
//求最大值
fun max (x: int list)=
if null x
then NONE
else
let fun max_nonempty( x: int list) =
if null (tl x)
then hd x
else
let val tl_ans = max_nonempty(tl x)(*防止重复递归*)
in
if hd x > tl_ans
then hd x
else tl_ans
end
in
SOME(max_nonempty x)(*单个参数可不加括号*}
WEEK3
datatype
case x of
Call1 => e1
| Call2(Str) => e2
| Call3(a,b) => e3
别名: type foo = int*bool
list, option 实质都是 datatype
- 例如 list的constructor是 SOME 和 NONE
- datatype 'a mylist = Cons of 'a * ('a mylist) | Empty
‘a , ‘b … 是泛型
pattern matching
类型推断
pattern matching 不仅可以匹配one of类型(用case of),还可以匹配each of类型(tuple,records等),此时使用case of有些累赘,故可以直接用val来匹配
fun full_name (r : {first:string,middle:string,last:string}) =
case r of
{first=x,middle=y,last=z} => x ^ " " ^ y ^ " " ^z
//等价于
fun full_name (r : {first:string,middle:string,last:string}) =
let val {first=x,middle=y,last=z} = r
in
x ^ " " ^ y ^ " " ^z
end
更进一步
fun f(t: int * int * int) =
case t of (x, y, z) => x + y + z;
//可以简写成
fun sum_triple (x,y,z) =
x + y + z
exception BadTriple
fun zip3 list_triple =
case list_triple of
([],[],[]) => [] //避免了大量的case of
| (hd1::tl1,hd2::tl2,hd3::tl3) => (hd1,hd2,hd3)::zip3(tl1,tl2,tl3)
| _ => raise BadTriple
fun unzip3 lst =
case lst of
[] => ([],[],[])
| (a,b,c)::tl => let val (l1,l2,l3) = unzip3 tl
in
(a::l1,b::l2,c::l3)
end
exception
尾递归
fun rev2 lst =
let fun aux(lst,acc) =
case lst of
[] => acc //accumulator
| x::xs => aux(xs, x::acc)
in
aux(lst,[])
end
WEEK4
//等价
fun increment x = x + 1
val increment = fn x => x+1
//第一个函数中String.size在每一次递归时都计算了一次,而第二个则只计算一次
fun allShorterThan1 (xs,s) =
filter(fn x => String.size x < String.size s, xs)
fun allShorterThan2 (xs,s) =
let val i = String.size s
in filter(fn x => String.size x < i, xs) end
fun fold f = fn acc => fn xs =>
case xs of
[] => acc
| x::xs' => fold f (f(acc,x)) xs'
//等价
fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i
val sqrt_of_abs = Math.sqrt o Real.fromInt o abs
fun sqrt_of_abs i = i |> abs |> Real.fromInt |> Math.sqrt
//等价
fun sum1 xs = fold (fn (x,y) => x+y) 0 xs
val sum2 = fold (fn (x,y) => x+y) 0
mutation
val x = ref 0
!x
x := (!x) + 7
callbacks
ADT
闭包
WEEK5:
open MyModule
来直接引用structure MyModule =
struct
bindings
end
type
foo signature SIGNAME =
sig
types-for-bindings
end
//实现接口
structure MyModule :> SIGNAME =
struct
bindings
end
datatype t1 = Foo of int | Bar of t2
and t2 = Baz of string | Quux of t1
fun no_zeros_or_empty_strings_t1 x =
case x of
Foo i => i <> 0
| Bar y => no_zeros_or_empty_strings_t2 y
and no_zeros_or_empty_strings_t2 x =
case x of
Baz s => size s > 0
| Quux y => no_zeros_or_empty_strings_t1 y