gpt4 book ai didi

haskell - 在 Haskell 函数中返回类的实例

转载 作者:行者123 更新时间:2023-12-04 16:39:42 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Return specific type within Haskell

(3 个回答)


8年前关闭。




如果函数的返回是 class ClassA , 是否可以在这样的函数中返回 ClassA 的任何实例? ?例如:someFunction :: (ClassA a) => String -> a
那么,为什么下面的这个功能不起作用呢?请注意 StringEq 的一个实例

getAnyEq :: (Eq a) => String -> a
getAnyEq input |input == "1" = "something"
|otherwise = "other"

发生的错误是:
Could not deduce (a ~ [Char])
from the context (Eq a)
bound by the type signature for getAnyEq :: Eq a => String -> a
at src/InterceptorRegistry.hs:11:13-33
`a' is a rigid type variable bound by
the type signature for getAnyEq :: Eq a => String -> a
at src/InterceptorRegistry.hs:11:13

我试图在 Internet 资源上找到这个确切的解释,但我没有找到……你能给我看一些吗?

最佳答案

类型Eq a => a并不意味着“实现 Eq 的类型”,而是“实现 Eq 的任何类型。例如,如果您使用未定义的函数实现:

getAnyEq :: (Eq a) => String -> a
getAnyEq str = undefined

以下函数可以正确编译(尽管在运行时会因未定义的错误而崩溃):
x,y,z :: Bool
x = getAnyEq "test" == "hello"
y = getAnyEq "test" == [Just (Right True)]
z = getAnyEq "test" == ("this", "sss")

由于无法为结果生成值,因此无法对您的函数进行体面的实现。

仅当类型变量具有包含返回值的函数的类的实例时,返回类型变量的函数才有意义。例如考虑 Num 类:
class (Eq a, Show a) => Num a where
(+) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a

(注意我是在一个非常旧的 ghc 版本上测试这个,你的 Num 可能没有 Eq 或 Show 约束)。

函数 fromInteger返回一个 a(不需要 a 作为输入),所以我们可以得到一个 a从那个类型类。一旦有了值,就可以使用其他函数。因此,以下功能起作用:
getANum:: (Num a) => String -> a
getANum "zero" = fromInteger 0
getANum "asdf" = fromInteger 46
getANum _ = fromInteger 1

> getANum "asdf"
46

请注意,作为文字整数被有效地解析为 fromInteger <num> , fromInteger上述函数中的函数调用实际上并不是必需的。我只是将它们包括在内以展示它是如何工作的。

可用于检索值的其他常见类型类是:
  • Monad (使用 return )
  • Applicative (使用 pure )
  • Monoid (使用 mempty )
  • Read (使用 read 或其任何其他功能)
  • 关于haskell - 在 Haskell 函数中返回类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133584/

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