我有一些值的列表,我需要在其中找出哪种值是第一个:
type my_types =
| MAlpha
| MBeta of int list
| MGamma of string * int
let find_first where what =
List.iter ( fun m ->
| MAlpha ->
(* iterate frough "what" to find if it was asked to look and return it if it was *)
| (* do the same for all other types *)
) where;
;;
let main =
let where_to_find = [MGamma, MAlpha, MBeta] in
let what_to_find = [MAlpha, MBeta] in
(match (first_found where_to_find what_to_find) with
| MAlpha ->
(* should return this *)
)
;;
有没有办法在不触及 find_first 中所有类型的 MyType 的情况下这样做 - 是否可以比较两个值的类型? 谢谢。
最佳答案
您发布的代码无法编译,但我认为您正在寻找以下信息:
可以编写所谓的或模式,例如
(function MAlpha | MBeta _ -> ...)
.但是模式不是一等公民。您不能从列表构建模式(顺便说一下,
[MGamma, MAlpha, MBeta]
是您问题中无法编译的内容之一),也不能将模式作为参数传递给函数。但是,您可以构建并传递匹配模式的函数,因此如果您愿意更改函数
find_first
为what
使用函数而不是列表,使用起来会更方便。
关于OCaml:查找特定类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538777/