简体   繁体   English

Haskell - 签名和类型错误

[英]Haskell - Signature and Type error

I'm new to Haskell and I'm having some trouble with function signature and types.我是 Haskell 的新手,我在函数签名和类型方面遇到了一些问题。 Here's my problem:这是我的问题:

I'm trying to make a list with every number between 1 and 999 that can be divided by every numeral of it's own number.我试图用 1 到 999 之间的每个数字制作一个列表,这些数字可以除以它自己数字的每个数字。 For example the number 280 can be in that list because 2+8+0=10 and 280/10 = 28 ... On the other hand 123 can't because 1+2+3=6 and 123/6=20,5.例如,数字 280 可以在该列表中,因为 2+8+0=10 和 280/10 = 28 ...另一方面,123 不能,因为 1+2+3=6 和 123/6=20, 5. When the final operation gives you a number with decimal it will never be in that list.当最后的操作给你一个十进制的数字时,它永远不会出现在那个列表中。

Here's my code:这是我的代码:

let inaHelper x = (floor(x)`mod`10)+ (floor(x/10)`mod`10)+(floor(x/100)`mod`10)

This first part will only do the sum of every numeral of a number.第一部分只会对数字的每个数字求和。 And this part works...这部分工作...

Here's the final part:这是最后一部分:

let ina = [x | x <- [1..999] , x `mod` (inaHelper x) == 0   ]

This final part should do the list and the verification if it could be on the list or not.最后一部分应该列出清单并验证它是否在清单上。 But it's give this error:但它给出了这个错误:

No instance for (Integral t0) arising from a use of ‘it’
    The type variable ‘t0’ is ambiguous
    Note: there are several potential instances:
      instance Integral Integer -- Defined in ‘GHC.Real’
      instance Integral Int -- Defined in ‘GHC.Real’
      instance Integral Word -- Defined in ‘GHC.Real’
    In the first argument of ‘print’, namely ‘it’
    In a stmt of an interactive GHCi command: print it


...
ina = [x | x <- [1..999] , x `mod` (inaHelper x) == 0   ]

What is the type of x ? x的类型是什么? Integer ? Integer ? Int ? Int Word ? Word The code above is very generic, and will work on any integral type.上面的代码非常通用,适用于任何整数类型。 If we try to print its type we get something like this如果我们尝试打印它的类型,我们会得到这样的结果

> :t ina
ina :: (Integral t, ...) => [t]

meaning that the result is a list of any type t we want, provided t is an integral type (and a few other constraints).这意味着结果是我们想要的任何类型t的列表,前提是t是一个整数类型(以及一些其他约束)。

When we ask GHCi to print the result, GHCi needs to choose the type of x , but can not decide unambiguously.当我们要求 GHCi 打印结果时,GHCi 需要选择x的类型,但不能明确决定。 This is what the error message states.这就是错误消息所述的内容。

Try specifying a type when you print the result.打印结果时尝试指定类型。 Eg例如

> ina :: [Int]

This will make GHCi choose the type t to be Int , removing the ambiguity.这将使 GHCi 选择类型tInt ,消除歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM