Kernael
Kernael

Reputation: 3280

OCaml - Reverse a list

I'm trying to implement my own list module as follows :

type 'a my_list =
    | Item of ('a * 'a my_list)
    | Empty

I've already implemented several functions and am now trying to create a list reversing function for my module which would look like this :

let rec rev = function
    | Empty             -> (*return reversed list*)
    | Item(i, remnant)  -> (*recursive call to rev*)

Moreover, I'm not supposed to use list operators such as '::', '[]' and '@'.

Edit, what I tried :

let rec rev_append l1 l2 = match l1 with
    | Empty             -> l2
    | Item(i, remnant)  -> rev_append remnant Item(i, l2)

let rev l = rev_append l Empty;;

But this is not working, there is an error at the second argument passed to the recursive call : "Item(i, l2)" The error is "The constructor Item expects 1 argument, but is here applied to 0 arguments".

Upvotes: 1

Views: 4394

Answers (1)

hivert
hivert

Reputation: 10667

Parenthesis man !

let rec rev_append l1 l2 = match l1 with
    | Empty             -> l2
    | Item(i, remnant)  -> rev_append remnant (Item (i, l2))

The compiler understood that rev_append was passed three argument namely remnant Item and (i, l2).

Upvotes: 1

Related Questions