类型:(数字a,数字a)与(数字a)? [英] Types: (Num a, Ord a) versus (Int a)?
问题描述
在一个文件中,我试图定义一个这样的函数:
myReplicate ::(Int a)= > a - > b - > [b]
myReplicate n x
| n< = 0 = []
|否则= x:myReplicate(n-1)x
当我尝试将文件加载到ghci时购买,我得到这个错误:
ghci>:l 1.hs
[1 of 1] Compiling Main(1。 hs,解释)
1.hs:38:17:
'Int'应用于太多类型参数
在'myReplicate'的类型签名中:
myReplicate :: Int a => a - > b - > [b]
失败,模块加载:无。
ghci告诉我myReplicate的类型应该是:
ghci>:t myReplicate
myReplicate ::(Num a,Ord a)=> a - > a1 - >如果我将类型声明更改为ghci推荐的内容:
b
myReplicate ::(Num a,Ord a)=> a - > b - > [b]
...然后函数编译和'工作'。然而,它是这样工作的:
ghci> myReplicate 3.2 1
[1,1,1,1 ]
为什么我不能声明myReplicate只将Int作为第一个参数Int下降(?)来自Ord类的事实)?我想我可以把我的第一个后卫改成x< 1,这样myReplicate 3.2 1会生成[1,1,1,],但为什么我必须打扰浮动?
解决方案 Int是一个类型,而不是一个类型类型。你想要的是
myReplicate :: Int - > b - > [b]
或者可能更精确的是
myReplicate :: Int - > Int - > [int]
这是一个关于类型和类型类的好教程:http://learnyouahaskell.com/types-and-typeclasses
In a file, I'm trying to define a function like this:
myReplicate :: (Int a) => a -> b -> [b]
myReplicate n x
| n <= 0 = []
| otherwise = x : myReplicate (n-1) x
Buy when I try loading the file into ghci, I get this error:
ghci>:l 1.hs
[1 of 1] Compiling Main ( 1.hs, interpreted )
1.hs:38:17:
`Int' is applied to too many type arguments
In the type signature for `myReplicate':
myReplicate :: Int a => a -> b -> [b]
Failed, modules loaded: none.
ghci tells me that the type of myReplicate should be:
ghci>:t myReplicate
myReplicate :: (Num a, Ord a) => a -> a1 -> [a1]
If I change the type declaration to what ghci recommends:
myReplicate :: (Num a, Ord a) => a -> b -> [b]
...then the function compiles and 'works'. However, it 'works' like this:
ghci>myReplicate 3.2 1
[1,1,1,1]
Why can't I declare that myReplicate only takes an Int as the first argument (also in light of the fact that Int descends(?) from the Ord class)? I guess I could change my first guard to be x < 1, so that myReplicate 3.2 1 would produce [1, 1, 1,], but why do I have to bother with floats?
解决方案 Int is a type, not a typeclass. What you want is
myReplicate :: Int -> b -> [b]
or probably more precisely
myReplicate :: Int -> Int -> [Int]
Here is a good tutorial on types and typeclasses: http://learnyouahaskell.com/types-and-typeclasses
这篇关于类型:(数字a,数字a)与(数字a)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!