tutorial1.
sml Page 1
fun sumList x =
if x = nil then 0
else hd(x) + sumList(tl(x));
sumList [1,2,3,4];
fun sumList1(y:int list):int =
case y of
nil => 0
| x::xs => x + sumList1(xs);
sumList1 [1,2,3,4];
(* sum all the real elements of the list *)
fun sumRealList(x:real list):real =
case x of
nil => 0.0
| y::ys => y + sumRealList(ys)
(* add 3 to all the int elements of the list *)
fun add3 [] = []
| add3 (x::xs) = (x+3)::add3(xs)
(* add 3 to all the int elements of the list *)
(* different style of implementing add3 *)
fun addInt3(x:int list):int list =
case x of
nil => []
| y::ys => (y+3)::addInt3(ys)
(* add 3.0 to all the real elements of the list *)
fun addReal3(x:real list):real list =
case x of
nil => []
| y::ys => (y+3.0)::addReal3(ys)
fun square x = x*x;
fun applySomeFunc (f, []) = []
| applySomeFunc (f, (x::xs)) = f(x) :: applySomeFunc(f, xs)
val t = [1, 3, 5, 7, 9] ;
applySomeFunc(square, t) ;
applySomeFunc(square, [1,2,3,4,5]) ;
fun rsquare(x:real):real = x*x;
applySomeFunc(rsquare, [1.0, 2.0, 4.0]);
(* use anonymous function to add 1 to all elements in the list *)
applySomeFunc((fn x=>x+1), [1,2,3,4,5]);
(* use anonymous function to cal x^3 to all elements in the list *)
applySomeFunc((fn x=>x*x*x), [1,2,3,4,5]);
(* use op+ to calculate the sum of a list *)
fun sumList x = foldl op+ 0 x;
sumList [1,2,3,4,5,6,7,8,9];
(* use op* to calculate the product of a list *)
fun prodList x = foldl op* 1 x;
prodList [1,2,3,4,5,6];
(* use op^ to concat a list *)
fun concatL x = foldl op^ "" x;
fun concatR x = foldr op^ "" x;
concatL ["Hello", "World"];
concatR ["Hello", "World"];
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:real list):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 =
let
val 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 = 1 then "January"
else if x=2 then "February"
else if x=3 then "March"
else "Bad month"