gpt4 book ai didi

ocaml - 具有多种返回类型的函数 : is it possible?

转载 作者:行者123 更新时间:2023-12-01 08:14:28 27 4
gpt4 key购买 nike

我有以下代码,我想返回一个 bool 值或一个元组。 (函数 isvariabledont_care 都返回 bool 值,仅供引用)

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 中是不可能的,更重要的是,我们不想在 OCaml 中拥有它。

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

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

使用这个新的求和类型,您的代码应该如下所示:

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;;

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

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 *)

关于ocaml - 具有多种返回类型的函数 : is it possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14764786/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com