可以说我有一个整数类型的列表[1; 2; 3; 4; 5; 6; 7; 8],我想一次模式匹配前三个元素。没有嵌套的match语句,有没有办法做到这一点?
例如,可以这样做吗?
let rec f (x: int list) : (int list) =
begin match x with
| [] -> []
| [a; b; c]::rest -> (blah blah blah rest of the code here)
end
我可以使用长嵌套的方法,它是:
let rec f (x: int list) : (int list) =
begin match x with
| [] -> []
| h1::t1 ->
begin match t1 with
| [] -> []
| h2::t2 ->
begin match t2 with
| [] -> []
| t3:: h3 ->
(rest of the code here)
end
end
end
谢谢!
最佳答案
是的,你可以这么做。语法如下:
let rec f (x: int list) : (int list) =
begin match x with
| [] -> []
| a::b::c::rest -> (blah blah blah rest of the code here)
end
但是您会注意到,如果列表中的元素少于三个,则此操作将失败。您可以为单个和两个元素列表添加案例,也可以仅添加与任何内容匹配的案例:
let rec f (x: int list) : (int list) =
match x with
| a::b::c::rest -> (blah blah blah rest of the code here)
| _ -> []
关于Ocaml模式一次匹配列表中的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4776065/