Exercise 3 Define a function less of type int int list in
Exercise 3: Define a function less of type int * int list - > int list so that less (e, L) is a list of all the integers in L that are less than e.
Solution
/** Lets Describing a function member of type \'\'a * \'\'a list -> bool so that member(e, L) is true if and only if e is an element of the given list L. *\\) (/* Correct, but non-pattern matching version is : fun member (e, L) = if null L then false else if e = hd(L) then true else member (e, tl(L)); /*) fun member (e, nil) = false | member (e, y::ys) = if (e=y) then true else member(e, ys); member (1, []); member (1, [1, 2]); member (1, [2, 1, 3]); member (1, [2, 3]); (/* Describing a function less of type int * int list -> int list so that less (e, L) is a list of all the integers in L that are less than e /*) (*/ Correct, but non-pattern matching version: fun less (e, L) = if null L then nil else if hd(L) < e then hd(L) :: less(e, tl(L)) else less (e, tl(L)); *) fun less (e, nil) = nil | less (e, y::ys) = if y < e then y :: less(e, ys) else less (e, ys); (*/ Define a function repeats of type \'\'a list -> bool so that repeats (L) is true if and only if the list L has two equal elements next to each other *) (*/ Correct, but non-pattern matching version: fun repeats (L) = if null L or else null(tl(L)) then false else if hd(L) = hd(tl(L)) then true else repeats (tl(L)); *) fun repeats (nil) = false | repeats (y::nil) = false | repeats (y::ys) = if y = hd(ys) then true else repeats(ys);
