1
type 'a mylist = 'a listcell ref
and 'a listcell = Nil | Cons of 'a * ('a mylist)

let l1 = (ref (Cons (1, ref (Cons (2,ref Nil)))))
let l2 = (ref (Cons(3, ref (Cons(4, ref Nil)))))

let rec append l1 l2 =
match l1 with
 | {contents = Nil} -> (l1 := !l2; l1)
 | {contents = Cons(h,t)} -> append t l2

this is what i've got so far, the goal is to append l2 to l1 i can traverse to the end of l1 and replace the ref with l2... which is what i was trying to do. but for some reason i lose everything that came before that.

any help would be appreciated, thanks

gallais
  • 11,823
  • 2
  • 30
  • 63
nachos
  • 69
  • 5

1 Answers1

2

When you reach the end of the list through recursive calls, l1 refers to the Nil element of the first list, not the beginning of the first list.

You can fix this by using a helper function inside append that works like your current append function. But at the end it returns the original l1 from the outer append function.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108