Functional programming Ocaml-表达式的类型为';列表->';b列表,但表达式的类型应为';b名单
这是我的职责Functional programming Ocaml-表达式的类型为';列表->';b列表,但表达式的类型应为';b名单,functional-programming,ocaml,Functional Programming,Ocaml,这是我的职责 let rec helper inputList = function | [] -> [] | a :: b :: hd -> if a = b then helper ([b::hd]) else a :: helper (b:: hd) 它还不完整,但是我不明白为什么我在helper([b::hd])的标题中不断出现错误。我尝试了helper(b::hd)或helper(b::hd::[]),但都出现了错误。如何使其工作?当您使用函数时,您为函数的参数提
let rec helper inputList = function
| [] -> []
| a :: b :: hd -> if a = b then helper ([b::hd]) else a :: helper (b:: hd)
它还不完整,但是我不明白为什么我在helper([b::hd])的标题中不断出现错误。我尝试了helper(b::hd)或helper(b::hd::[]),但都出现了错误。如何使其工作?当您使用
函数时,您为函数的参数提供了一个模式。但是您已经有一个名为inputList
的参数。因此,这个函数helper
需要两个参数(但它忽略了第一个参数)
您可以通过删除inputList
来解决此问题
您在第一次递归调用helper
时也遇到了问题。表达式[b::hd]
是一个列表列表。我怀疑您想要的东西更像这里的b::hd
至少还有一个问题,但我希望这能帮助您开始。这里有多个错误。一个是关键字function
意味着我们有一个隐式参数,我们正在处理这个参数。所以模式匹配发生在“不可见”参数上。但在这里您可能定义了显式的:inputList
。因此,我们可以删除该选项:
let rec helper = function
| [] -> []
| a :: b :: hd -> if a = b then helper ([b::hd]) else a :: helper (b:: hd)
接下来,类型有一个问题:在递归中,您使用:
helper([b::hd])
;及
a::helper(b::hd)
但是你把它们放在同一行,这没有意义,因为第一行传递元素列表,第二行传递元素列表。第一个结果是元素列表,第二个结果是元素列表。将这些合并是没有意义的
如果我正确理解您希望确保不出现两个相等的连续元素,那么我们应该将其重写为:
let rec helper = function
| [] -> []
| a :: b :: hd -> if a = b then helper (b::hd) else a :: helper (b:: hd)
因为所有递归调用都会弹出列表的开头,所以最终该列表包含一个元素。
let rec helper = function
| [] -> []
| h :: [] -> h :: []
| a :: b :: hd -> if a = b then helper (b::hd) else a :: helper (b:: hd)