Ocaml模式一次匹配列表中的多个元素

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)

  • 你可以匹配,`a ::((b :: c :: rest)as tl)`然后你可以使用`tl`而无需重新创建列表的head元素. (2认同)