che*_*pro 8 ocaml design-patterns elements matching
假设我有一个整数类型列表[1; 2; 3; 4; 5; 6; 7; 我希望一次匹配前三个元素.没有嵌套的匹配语句有没有办法做到这一点?
例如,它可以这样做吗?
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
Run Code Online (Sandbox Code Playgroud)
我可以使用long嵌套方法,它将是:
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
Run Code Online (Sandbox Code Playgroud)
谢谢!
Nik*_*chi 11
是的,你可以这样做.语法是这样的:
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
Run Code Online (Sandbox Code Playgroud)
但是你会注意到如果列表少于三个元素,这将失败.您可以为单个和两个元素列表添加案例,也可以只添加与任何内容匹配的案例:
let rec f (x: int list) : (int list) =
match x with
| a::b::c::rest -> (blah blah blah rest of the code here)
| _ -> []
Run Code Online (Sandbox Code Playgroud)