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

标签 ocaml design-patterns elements matching

可以说我有一个整数类型的列表[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/

相关文章:

OCaml 空全局变量

polymorphism - OCaml:具有通用键的 map 上的多态函数

ocaml - 如何在 OCaml 中发送电子邮件,设置 `Content-Type: Multipart/Alternative`

design-patterns - 设计模式-建筑宇航员

javascript - 检测元素在屏幕上的百分比

types - Coq 到 OCaml 的代数类型提取

c# - DDD 中的服务和存储库 (C#)

java - 用 Class.forName() 初始化一个类,它有一个带参数的构造函数

r - 在 R 中的数据框列中使用向量

r - 如何检查矩阵是否是矩阵列表的元素?在 R