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

时间:2011-01-23 19:50:39

标签: 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

我可以使用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

谢谢!

1 个答案:

答案 0 :(得分: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

但是你会注意到,如果列表少于三个元素,这将失败。您可以为单个和两个元素列表添加案例,也可以只添加与任何内容匹配的案例:

let rec f (x: int list) : (int list) = 
  match x with
  | a::b::c::rest -> (blah blah blah rest of the code here)
  | _ -> []
相关问题