【问题标题】:Ocaml pattern matching multiple elements in a list at onceOcaml 模式一次匹配列表中的多个元素
【发布时间】:2011-06-14 03:32:19
【问题描述】:

假设我有一个整数类型列表 [1; 2; 3; 4; 5个; 6; 7; 8] 我想一次匹配前三个元素。没有嵌套的匹配语句有没有办法做到这一点?

例如,可以这样吗?

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

谢谢!

【问题讨论】:

    标签: ocaml design-patterns elements matching


    【解决方案1】:

    是的,你可以这样做。语法是这样的:

    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)
      | _ -> []
    

    【讨论】:

    • 酷,谢谢!让我们说(这里的代码的其余部分)我想返回除元素“a”之外的所有内容。我会做 b@c@rest 吗?
    • 您可以匹配a::((b::c::rest) as tl),然后您可以使用tl,而无需重新创建列表的头部元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多