Search code examples
recursionocamltrace

Tracing Ocaml Recursive Function


I'm having trouble tracing through this code (which is correct):

    let rec prepend (l: int list list) (x: int) : int list list = 
        begin match l with
          | [] -> []
          | hd :: tl -> (x :: hd) :: (prepend tl x)
        end

prepend [[]; [2]; [2;3]] 1 = [[1]; [1;2]; [1;2;3]]

My tracing is incorrect, but I'm not sure what's wrong:

prepend ([]::2::[]::2::3::[]::[]) 1 =
1::[]::prepend (2::[]::2::3::[]::[]) 1 =
1::[]::1::2::prepend([]::2::3::[]::[]) 1 =
1::[]::1::2::1::[]::prepend(2::3::[]::[]) 1 --> 
This is incorrect because then it comes out as [1] ; [1;2;1]
when it should be [1]; [1;2] ; [1;2;3]

Solution

  • The :: operator isn't associative, i.e., (a :: b) :: c is not the same as a :: (b :: c). So you should be using parentheses to keep track of your sublists.

    prepend ([] :: (2 :: []) :: (2 :: 3 :: []) :: []) 1 =>
    (1 :: []) :: prepend ((2 :: []) :: (2 :: 3 :: []) :: []) 1 => 
    (1 :: []) :: (1 :: 2 :: []) :: prepend ((2 :: 3 :: []) :: []) 1 => ...
    

    Maybe you can take it from there....