在 Haskell 中返回特定类型 [英] Return specific type within Haskell
问题描述
我有一个关于 Haskell 类型系统的非常普遍的问题.我正在努力熟悉它,我有以下功能:
I have a pretty general question about Haskell's type system. I'm trying to become familiar with it, and I have the following function:
getN :: Num a => a
getN = 5.0 :: Double
当我尝试编译它时,出现以下错误:
When I try to compile this, I get the following error:
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 是可以的.
As I understand this, the function is set up to "return" a type in the class Num. Double is in this class (http://www.zvon.org/other/haskell/Outputprelude/Num_c.html), so I would have expected that it would be okay to "return" a Double in this case.
有人可以解释一下吗?
推荐答案
带有签名的函数 Num a =>a
预计适用于 Num
类中的 任何 类型.实现 5.0 :: Double
仅适用于 one 类型,而不适用于该类的 所有 类型,因此编译器会抱怨.
A function with signature Num a => a
is expected to work for any type in the class Num
. The implementation 5.0 :: Double
just works for one type, not for all types of the class, so the compiler complains.
一个通用函数的例子是:
An example of a generic function would be:
square :: (Num a) => a -> a
square x = x * x
这适用于 任何 类型的 Num
.它适用于双精度数、整数和您想使用的任何其他数字.因此,它可以有一个泛型类型签名,只需要参数在 Num
类中.(类型类 Num
是必需的,因为该函数使用与 *
的乘法,在那里定义)
This works for any type that is a Num
. It works for doubles, integers and whatever other numbers you want to use. Because of that it can have a generic type signature that just requires the parameter to be in class Num
. (Type class Num
is necessary because the function uses multiplication with *
, which is defined there)
这篇关于在 Haskell 中返回特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!