今天做了 coursera: 程序設計語言 的第一章的作業(yè)妓羊。
作業(yè)我就不放在這里了绊起。但是我為了寫作業(yè)腔彰,寫了幾個通用的小函數(shù)芍阎,放在這里備忘吧世曾。
函數(shù)們
(*List的flatMap*)
fun flatMap f xs = List.concat(map f xs)
(*其實還有更賤兮兮的寫法,最好到此為止,不要繼續(xù)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