Search code examples
ocamlreversecons

What is wrong with this OCAML function?


Here is my original code.

let rec reverse l =
   match l with 
   | [] -> []
   | (h::t) -> (reverse t) :: h

Solution

  • The cons :: operator takes an element as left-hand argument and a list as right-hand argument. Here, you do the opposite which does not work.

    The right way to add an element at the element at the end of a list is to use list concatenation:

    let rec reverse l =
      match l with
      | [] -> []
      | h :: t -> (reverse t) @ [h]
    

    That code is not optimal though, and you may want to make it tail recursive.