在一个文件中,我试图定义一个这样的函数:
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]这是一个关于类型和类型类的好教程:learnyouahaskell/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) xBuy 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: learnyouahaskell/types-and-typeclasses
更多推荐
类型:(数字a,数字a)与(数字a)?
发布评论