【问题标题】:Matching tuples of varying length and type (ocaml)匹配不同长度和类型的元组 (ocaml)
【发布时间】:2015-04-02 00:58:16
【问题描述】:

我在模式匹配不同长度和类型的元组时遇到问题。

let test = ((6, 10), (3, "1", 9), ([2; "5"], 4, 7, "8"));;
let rec extract_min_int arg =
    match arg with
    | (a, b, c) ->
        min (extract_lowest_int a) (min (extract_lowest_int b) (extract_lowest_int c))
    | (a, b) -> min (extract_lowest_int a) (extract_lowest_int b)
    | `int i -> i
    | _ -> infinity
;;
extract_min_int test;;

我希望此函数调用返回 2,但我收到以下错误:

错误:此模式匹配 'a * 'b 类型的值,但预期的模式匹配 'c * 'd * 'e 类型的值

我对 ocaml 还很陌生。这个错误完全否认了我正在尝试做的事情,即匹配不同长度/类型的元组。

我还有哪些其他选择可以完成这项任务?

【问题讨论】:

  • 嗯,你为什么要创建这样的数据混乱?顺便说一句,let test = 中有一个错字。而且你无法匹配它,因为它没有结构(看起来像那样)

标签: types pattern-matching tuples ocaml


【解决方案1】:

OCaml 是一种强类型语言。每个元组大小都是不同的类型。所以你不能写出你想要的函数。

如果您想到了特定的类型元组,则可以仅使用这些类型的组合来定义变体类型。这就是你在实践中可能会做的事情。

【讨论】:

    猜你喜欢
    • 2012-09-23
    • 2019-03-27
    • 2015-05-28
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多