OCaml:查找特定类型的值

标签 ocaml static-typing

我有一些值的列表,我需要在其中找出哪种值是第一个:

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 的情况下这样做 - 是否可以比较两个值的类型? 谢谢。

最佳答案

您发布的代码无法编译,但我认为您正在寻找以下信息:

  1. 可以编写所谓的或模式,例如 (function MAlpha | MBeta _ -> ...) .

  2. 但是模式不是一等公民。您不能从列表构建模式(顺便说一下,[MGamma, MAlpha, MBeta] 是您问题中无法编译的内容之一),也不能将模式作为参数传递给函数。

  3. 但是,您可以构建并传递匹配模式的函数,因此如果您愿意更改函数 find_firstwhat 使用函数而不是列表,使用起来会更方便。

关于OCaml:查找特定类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538777/

相关文章:

python - python3 : list vs List中的静态类型

ocaml - 如何在 OCAML 中获取 Uint64 的二进制表示

ocaml - 无法使用 s 表达式

ocaml - 为什么 "if"在我的代码中是意外标记?

python - 如何在 Cython 中有效地使用 Python 风格的整数?

c++ - 异常对象的静态类型

typescript - addEventListener mousemove 及其事件参数的正确 typescript 类型是什么?

Ocaml:FIFO 读取不正确

floating-point - OCaml 中的 80 位扩展精度浮点

c# - float 比双倍慢吗? 64位程序运行速度比32位程序快吗?