【问题标题】:Function with multiple return types: is it possible?具有多种返回类型的函数:可能吗?
【发布时间】:2013-02-08 02:29:34
【问题描述】:

我有以下代码,我想返回一个布尔值或元组。 (函数isvariabledont_care 都返回布尔值,仅供参考)

let match_element (a, b) =
if a = b then true
else if (dont_care a) || (dont_care b) then true
else if (isvariable a) then (a, b)
else if (isvariable b) then (b, a)
else false;;

目前,它会引发以下错误:

有没有办法解决这个问题?

This expression has type 'a * 'b
but an expression was expected of type bool

(这个函数是基于Python程序的指令,我不确定在OCaml中是否可行。)

【问题讨论】:

    标签: ocaml strong-typing


    【解决方案1】:

    粗略地说,您想要的是临时多态性或重载。在 OCaml 中是不可能的,更重要的是,我们不想在 OCaml 中拥有它。

    如果你想要一个返回多种类型的函数,那么你必须定义一个新的“sum”类型来表达这些类型:这里,你想要返回一个布尔值或元组,所以一个新类型意味着“布尔值或元组”。在 OCaml 中,我们定义了这样一个类型:

    type ('a, 'b) t = Bool of bool
                    | Tuple of 'a * 'b
    

    使用这种新的 sum 类型,您的代码应如下所示:

    type ('a, 'b) t = 
      | Bool of bool
      | Tuple of 'a * 'b
    
    let match_element (a, b) =
      if a = b then Bool true
      else if dont_care a || dont_care b then Bool true
      else if is_variable a then Tuple (a, b)
      else if is_variable b then Tuple (b, a)
      else Bool false;;
    

    这里的类型 t 带有两个参数('a 和 'b)对于您的目的来说可能过于笼统,但我无法从上下文中猜出您想要做什么。可能有更好的类型定义适合您的意图,例如:

    type element = ... (* Not clear what it is from the context *)
    
    type t =
      | I_do_not_care        (* Bool true in the above definition *)
      | I_do_care_something  (* Bool false in the above definition *)
      | Variable_and_something of element * element  (* was Tuple *)
    

    【讨论】:

    • 谢谢!最终的解决方案是改用 Python。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多