Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml Type Error For enumerate example

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!

like image 369
Emir Arditi Avatar asked May 24 '26 07:05

Emir Arditi


1 Answers

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)
like image 126
Tarmil Avatar answered May 26 '26 18:05

Tarmil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!