我一直在努力奋斗半个多小时.我知道这很简单,但我对Haskell中的类型很糟糕,即使在阅读了与我非常相似的问题的公认答案之后,我仍然无法解决我的问题 - 更不用说了解它!
代码:
p108 = [filter (\[a,b] -> a>0 && b>0) (diophantinepairs n) | n <- [1..]]
diophantinepairs :: Integer -> [[Integer]]
diophantinepairs n = nub$map sort b
where
a = divisors n
b = [[(n-d), n - (n^2)/d] | d <- a]
Run Code Online (Sandbox Code Playgroud)
错误 :
Run Code Online (Sandbox Code Playgroud)249:39: No instance for (Fractional Integer) arising from a use of `/' Possible fix: add an instance declaration for (Fractional Integer) In the second argument of `(-)', namely `(n ^ 2) / d' In the expression: n - (n ^ 2) / d In the expression: [(n - d), n - (n ^ 2) / d]
谢谢,山姆.
以下是您阅读这些错误的方法:
No instance for (Fractional Integer)
Run Code Online (Sandbox Code Playgroud)
翻译:你的程序有一个Integer,但你正在使用其中一个方法Fractional.
arising from a use of `/'
Run Code Online (Sandbox Code Playgroud)
翻译:涉及的方法是/,这是Fractional课程的一部分. Integer不是Fractional,所以你不能申请/一个整数.
解决方案:使用div或quot替代.
我可以ghci很容易地得到同样的错误:
Prelude> (1 :: Integer) / (2 :: Integer)
<interactive>:2:16:
No instance for (Fractional Integer)
arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Integer)
In the expression: (1 :: Integer) / (2 :: Integer)
In an equation for `it': it = (1 :: Integer) / (2 :: Integer)
Run Code Online (Sandbox Code Playgroud)
替代修复:使用Fractional诸如a之类的类型Rational而不是Integer:
Prelude> (1 :: Integer) `div` (2 :: Integer)
0
Prelude> :m + Data.Ratio
Prelude Data.Ratio> (1 :: Rational) / (2 :: Rational)
1 % 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |