问题描述
我正在尝试在OCaml中编写一个函数,以从任何给定列表中删除连续的重复项。我相信我已经找到了正确的递归函数,但是当我尝试使用int list
或string list
对其进行测试时,它告诉我我的函数正在使用类型'a list
。任何帮助将不胜感激。
这是我的代码:
let compress l =
let rec compress_loop l cl e =
match l with
|[] -> cl
|h::t -> if(h == e) then
compress_loop t cl h
else
compress_loop t (List.append cl h) h
in
compress_loop l [] [];;
compress ["a";"b"];;
解决方法
根本问题是此处给出的最后一个参数:compress_loop l [] []
。由于您将其传递为空列表,因此e
的类型必须为'a list
。并且由于您将e
与h
中的if(h == e) then
进行比较,因此h
也必须是'a list
。并且由于h
是从l
(也是一个列表)中解构而成的,因此l
必须具有类型'a list list
。
因此,当您给它一个string list
时,编译器会告诉您它期望元素的类型为'a list
,而不是string
。