AndroidNewbie
AndroidNewbie

Reputation: 25

What is wrong with this OCAML function?

Here is my original code.

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

Upvotes: 0

Views: 447

Answers (1)

PatJ
PatJ

Reputation: 6144

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.

Upvotes: 3

Related Questions