gpt4 book ai didi

haskell - 返回 Haskell 中的特定类型

转载 作者:行者123 更新时间:2023-12-02 09:59:46 24 4
gpt4 key购买 nike

我有一个关于 Haskell 类型系统的非常普遍的问题。我正在尝试熟悉它,并且我有以下功能:

getN :: Num a => a
getN = 5.0 :: Double

当我尝试编译它时,出现以下错误:

Couldn't match expected type `a' against inferred type `Double'
`a' is a rigid type variable bound by
the type signature for `getN' at Perlin.hs:15:12
In the expression: 5.0 :: Double
In the definition of `getN': getN = 5.0 :: Double

据我了解,该函数设置为“返回”类 Num 中的类型。 Double 属于此类 ( http://www.zvon.org/other/haskell/Outputprelude/Num_c.html ),因此我预计在这种情况下“返回” Double 是可以的。

有人可以解释一下吗?

最佳答案

具有签名 Num a => a 的函数预计适用于 Num 类中的任何类型。实现 5.0::Double 仅适用于一个类型,而不适用于该类的所有类型,因此编译器会提示。

通用函数的一个例子是:

square :: (Num a) => a -> a
square x = x * x

这适用于 Num任何类型。它适用于 double 、整数以及您想要使用的任何其他数字。因此,它可以有一个通用类型签名,只需要参数位于类 Num 中。 (类型类 Num 是必需的,因为该函数使用与 * 的乘法,这是在此处定义的)

关于haskell - 返回 Haskell 中的特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1534224/

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