今天做了 coursera: 程序设计语言 的第一章的作业。
作业我就不放在这里了。但是我为了写作业,写了几个通用的小函数,放在这里备忘吧。
函数们
(*List的flatMap*)
fun flatMap f xs = List.concat(map f xs)
(*其实还有更贱兮兮的写法,最好到此为止,不要继续point free了*)
fun flatMap f = List.concat o map f
(*然后定义符号,infix相当于infixl*)
infix 1 >>=
fun xs >>= f = flatMap f xs
(*List的scan*)
fun scan f [] = []
| scan f (x::xs) =
let
fun scan' init f [] = init :: []
| scan' init f (x::xs) =
let
val next = f(init,x)
in
init :: scan' next f xs
end
in
scan' x f xs
end
fun id x = x;
(*依赖id*)
fun range2(m:int, n:int) = let
val a = Int.min(m,n)
val b = Int.max(m,n)
val f = if m<n then id else rev
fun rang(p:int,q:int) = case q=p of
true => []
| false => p :: rang(p+1,q)
in f(rang(a,b))
end
fun range x = List.tabulate(x, fn x => x)
(* 依赖range *)
fun findIndex f xs =
let
val len = length xs
val indexes = range len
val ixs = ListPair.zipEq (indexes, xs)
fun ff (i,x) = f x
val ix = List.find ff ixs
fun getI (i,x) = i
val x = Option.map getI ix
in
x
end
fun removeDuplicates xs =
let
fun f(x,xs) = if(List.exists (fn i => x = i) xs) then xs else x::xs
in
rev(foldl f [] xs)
end
使用示例
- range(0);
val it = [] : int list
- range(5);
val it = [0,1,2,3,4] : int list
- range2(1,3);
val it = [1,2] : int list
- range2(3,~1);
val it = [2,1,0,~1] : int list
- scan op+ [1,2,3];
val it = [1,3,6] : int list
- scan op+ [1,2,3,1,2];
val it = [1,3,6,7,9] : int list
- scan op+ [];
val it = [] : int list
- scan op+ [1];
val it = [1] : int list
- findIndex (fn x => x=3) [1,2,3];
val it = SOME 2 : int option
- findIndex (fn x => x=3) [];
val it = NONE : int option
- findIndex (fn x => x=3) [1,2,4];
val it = NONE : int option
网友评论