OCaml - Reverse a list

筅森魡賤 提交于 2019-12-23 04:02:56

问题


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".


回答1:


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).



来源:https://stackoverflow.com/questions/22221053/ocaml-reverse-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!