类型:(数字a,数字a)与(数字a)?

编程入门 行业动态 更新时间:2024-10-28 16:17:15
本文介绍了类型:(数字a,数字a)与(数字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]

这是一个关于类型和类型类的好教程: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) 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: learnyouahaskell/types-and-typeclasses

更多推荐

类型:(数字a,数字a)与(数字a)?

本文发布于:2023-10-26 12:37:53,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!