OCaml-撤消列表 [英] 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 '@'.
编辑,我尝试过的:
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;;
但是这不起作用,传递给递归调用的第二个参数处有一个错误:"Item(i,l2)"该错误是构造函数Item期望有1个参数,但是这里应用于0个参数"
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".
推荐答案
肢体瘫痪的人!
let rec rev_append l1 l2 = match l1 with
| Empty -> l2
| Item(i, remnant) -> rev_append remnant (Item (i, l2))
编译器了解到rev_append
传递了三个参数,即remnant
Item
和(i, l2)
.
The compiler understood that rev_append
was passed three argument namely remnant
Item
and (i, l2)
.
这篇关于OCaml-撤消列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!