(c)
let rec len l =
match l with
[] -> 0
| (h::t) -> 1 + len t
(d)
let rec f (n,l) =
match l with
[] -> n
| (n,h::t) = if (h>n) then f (h,t) else f(n,t)
Solution: run Ocaml to get types.
--------
(a) Not tail recursive.
let map f l =
let rec helper (acc,l') =
match l' with
[] -> acc
| (acc,h::t) = helper((f h)::acc,t)
in
List.rev(helper([],l))
(b) Tail recursive.
(c) Not tail recursive.
let len l =
let rec helper (n,l') =
match l' with
[] -> n
| helper (n,_::t) = helper(s+1,t)
in
helper(0,t)
(d) Tail recursive.
_________________________________________________________________________
Problem 3:
---------
The following datatype can be used to represent arbitrarily nested
lists.
type 'a nlist = Nil | Cons of 'a elt * 'a nlist
and 'a elt = E of 'a | NL of 'a nlist
The list [1,2] could be represented as Cons(E 1,Cons(E 2,Nil)),
the list [[1],2] as Cons(NL(Cons((E 1),Nil)),Cons(E 2,Nil))
and the list [[[],[1]],2] as Cons(NL(Cons(NL Nil,Cons (E 1,Nil))), Cons(E 2,Nil)).
Using only pattern-matching (i.e. no if-then-else expressions):
(a) Write a function: nlist_toString: ('a -> string) -> 'a nlist -> string
such that if nl is bound to Cons(NL(Cons(NL Nil,Cons (E 1,Nil))), Cons(E 2,Nil)),
then (nlist_toString Int.toString nl) evaluates to: "[[[],[1]],2]".