3
votes

Hello I am new to OCaml And I am trying to learn the basic syntax of tail recursion. I wrote the following code in order to get a list and return the list with duples containing element and its index. for example ["b";"c";"dd";] -> [("b", 0); ("c", 1); ("dd", 2)]

I wrote the following code:

let enumerateWithTail lst =
  let rec inside lst acc index =
  match lst with
  | [] -> acc
  | x::xs -> inside xs (x,index)::acc (index+1)
 in inside lst [] 0;;

This doesn't work but my professors example(which at least I think its pretty similar) works. My professors code is:

let enumerate lst =
  let rec aux lst acc =
    match lst with
    | [] -> acc
    | x::xs -> let (eList, index) = acc
               in aux xs ((x, index)::eList, index+1)
  in List.rev(fst(aux lst ([], 0)))

Can someone please explain why my code gives the error: This expression has type 'a * 'b but an expression was expected of type 'c list

Thanks in advance!

1

1 Answers

6
votes

The problem is with precedence. Function application has higher precedence than any operator, including ::, so this:

inside xs (x,index)::acc (index+1)

is interpreted as:

(inside xs (x,index)) :: (acc (index+1))

whereas what you want is:

inside xs ((x,index)::acc) (index+1)