Tuesday, March 5, 2013

ML (Standard Meta Language New Jersey

Language: ML (Standard Meta Language, New Jersey)

Purpose:

Various book exercises from Modern Programming Languages: A Practical Introduction, by Adam Brooks Webber to be exposed to the functional language ML or SML.
(*Write a function min3 of type int * int * int -> int that 
returns the smallest of three integers.*)
(* BLOCK COMMENT *)
 
fun min3(a:int,b:int,c:int) =if ((a<b) andalso (a<c)) then a else (if (b<c) then b else c);
 
(*__________*)

(*Write a function cycle of type 'a list * int -> 'a list that taks a 
list and an integer n as input and returns the same list, 
but with the first element cycled to the end of the list n times. *)

fun cycle(num, a:int) = if (a<= 0) then num else  cycle(tl(num) @ [hd(num)], a-1);

(*I got marked down for this one since it didn't handle the nil list.*)


(*__________*)


 
(*Write a function isPrime of type int ->bool that returns 
true if and only if its integer parameter is a prime number. 
Your function need not behave well if the parameter is negative.
*)
 
fun isPrime(a:int) =if(a<2) then false else if (a = 2) 
then true else let fun recur (i)= if ( i * i > a) 
then true else if( ((a mod i )= 0) andalso (i <> a)) 
then false else (recur(i+1)) in recur 2 end;


(*Note that <> means 'not equal' in ML.*)

(*__________*)


(*Write a function select of type 'a list  * ('a -> bool ) -> a' 
list that takes a list and a function f as parameters. Your 
function should apply f to each element of the list and 
should return a new list containing only those elements of 
the original list for which f is returned true. (The elements 
of the new list may be given in any order.)*)

 

fun select (list, func) = if null list then [] else if func(hd list) then select (tl list,func) @ [hd list] else select(tl list, func);

(*Grader made this note to me GRADE: 14/15
fun select(nil,func) = nil | select(list,func) = ...*)

No comments:

Post a Comment