Ocaml使列表更浅一层(与list.singleton相反)

Ocaml使列表更浅一层(与list.singleton相反),list,ocaml,List,Ocaml,我有一个函数,它返回一个int list,如下所示: [[[1;2;3];[4;5];[]]] [[1;2;3];[4;5];[]] let f [x] = ... 并希望它返回该列表,并删除一组方括号,如下所示: [[[1;2;3];[4;5];[]]] [[1;2;3];[4;5];[]] let f [x] = ... 到目前为止,我掌握的代码是: let rec shallow [lst] : ('a list list) = match [lst] with

我有一个函数,它返回一个
int list
,如下所示:

[[[1;2;3];[4;5];[]]]
[[1;2;3];[4;5];[]]
let f [x] = ...
并希望它返回该列表,并删除一组方括号,如下所示:

[[[1;2;3];[4;5];[]]]
[[1;2;3];[4;5];[]]
let f [x] = ...
到目前为止,我掌握的代码是:

let rec shallow [lst] : ('a list list)  = 
    match [lst] with
    | [] -> ([]:'a list list)
    | ([]:'a list list) -> [[]]
    | [[]] -> []
    | [lst] -> lst
    | hd::tl::tl2 -> hd@tl@(shallow tl2);;
它给出了错误{引用案例
[lst]->(lst:'a list)
}
“此表达式的类型为“a列表”,但表达式的类型应为“a列表”。

请注意,如果您定义这样的函数:

[[[1;2;3];[4;5];[]]]
[[1;2;3];[4;5];[]]
let f [x] = ...
您的函数仅适用于长度为1的列表。对于任何其他输入,该函数将引发异常。编译器将警告您:

# let f [x] = x;;
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]
val f : 'a list -> 'a = <fun>
您的输入类型为“列表”,因此应更改为:

| ([]:'a list list list) -> [[]]

(但您可能需要考虑函数输入和输出的确切形式。)

感谢Jeffrey Scofield为我提供了回答此问题所需的提示:

let rec shallow (lst:'a list list list) : ('a list list) = 
     match lst with
     | [] -> []
     | h::t -> h@(shallow t);;

关于
List.concat
?如果您查看标准库(OCaml v4.03)的
List
模块,您会发现
flatten
函数的实现:
让rec flatte=function[]->[]| l::r->l@flatter
,这正是您的
浅层
函数(只是它更一般一点). 另外(正如pyon所提到的)
concat
也可以工作,因为它被定义为
让concat=flatten
。如果你这样定义它,就不需要有这么多级别的
列表<代码>让rec变浅(lst:“列表”)(“列表”)
将是相同的,但更一般。