smltutorial
TRANSCRIPT
-
8/6/2019 smlTutorial
1/2
-
8/6/2019 smlTutorial
2/2
tutorial1.sml Page 2
(* applySomeFunc is implemented in the system called map *)(* Currying *)
(* add n to each element of the list *)
fun addN(n, y)= map (fn x=>x+n) y;addN(3, [1,2,3]);
(* add n to each element of the list, remove parenthesis *)fun incN n y = map (fn x=>x+n) y;incN 3[1,2,3];
(* define a convenient function name to increment 10 *)
fun add10 x = incN 10 x;add10 [1,2,3,4,5];
fun sumRealList(x:reallist):real=case x of
nil => 0.0 | y::ys => y + sumRealList(ys)
(* find the roots of ax^2 + bx + c = 0 *)
fun roots(a:real, b:real, c:real):real*real=
letval rt =Math.sqrt(b*b - 4.0*a*c)
in ((~b + rt) / (2.0* a), (~b - rt) / (2.0* a))end
fun month(n:int):string=case n of
1=> "January" |2=> "February" |3=> "March" |4=> "April" |5=> "May" |6=> "June"
|7=> "July" |8=> "August" |9=> "September" |10=> "October" |11=> "November" |12=> "December" |_=> "Bad month"
(* different style of coding a function *)
fun month1 1="January" | month1 2="February" | month1 3="March" | month1_="Bad month"
(* different style of coding a function *)
fun month2 x =if x =1then"January"
elseif x=2then"February" elseif x=3then"March" else"Bad month"