大家好,我正在尝试在 Ocaml 中展平一个列表。我是新手,如果我的错误很愚蠢,请原谅我
例如,如果输入是 [[1];[2;3];[4]] 我应该以 [1;2;3;4] 结尾。
我尝试使用的想法如下用accumaltor = []从右边遍历列表(使用fold_right)伪代码如下
func flatten(list, accumalator)
For each item from right to left in list
If Item is a scalar then n :: accumalator
Else fi Item is a list of form head :: tail then
head :: flatten (tail, accumalator).
我认为理论上该算法是正确的,但如果您不同意,请告诉我。
现在到我的 OCaml 代码来实现这个算法
let rec flatten acc x =
match x with
n -> n :: acc
| [x] -> x :: acc
| head :: remainder ->
head :: ( my_flat acc remainder )
and my_flat = List.fold_right flatten
;;
my_flat [] [[1];[2;3];[4]]
我得到的错误是以下错误:此表达式的类型为 'a,但预期的表达式类型为
错误发生在 match 语句的最后一个模式中读取 head :: (my_flat acc remaining) 的行上
任何帮助表示赞赏。