返回Haskell中的特定类型 [英] Return specific type within Haskell
问题描述
我对Haskell的类型系统有一个相当普遍的问题。我试图熟悉它,并且我有以下功能:
getN :: Num a => a
getN = 5.0 :: Double
当我尝试编译这个时,以下错误:
无法匹配预期类型'a'与推断类型'Double'
`a'是一个刚性类型变量,由
绑定,在Perlin.hs中为`getN'的类型签名:15:12
在表达式中:5.0 :: Double
在`getN'的定义中:getN = 5.0 :: Double
据我所知,函数设置为返回在班级中。 Double在这门课上( http://www.zvon.org/other/ haskell / Outputprelude / Num_c.html ),所以我本以为在这种情况下可以返回一个Double。
有人可以请解释一下这个问题?
具有签名 一个通用函数的例子是: 这适用于任何类型是 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: When I try to compile this, I get the following error: 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. Can someone explain this please? A function with signature An example of a generic function would be: This works for any type that is a 这篇关于返回Haskell中的特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Num a =>预计
可用于类 Num
中的任何类型。实现 5.0 :: Double
只适用于一个类型,而不适用于全部类型的类型,因此编译器抱怨。
pre $ square ::(Num a)=> a - > a
square x = x * x
Num
。它适用于双打,整数和任何其他你想使用的数字。因为它可以有一个通用类型签名,只需要参数在类 Num
中。 (类型为 Num
是必要的,因为函数使用与在其中定义的 *
相乘)。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 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.square :: (Num a) => a -> a
square x = x * x
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)