我是一名有帮助的助手,可以为您提供翻译。以下是您需要翻译的内容:
我只是自学Haskell(出于兴趣),但遇到了难题。
我的问题:
如何定义一个函数
flrt = (floor . sqrt)
当我将其放入文件并编译时,GCHi会报以下错误:
AKS.hs:11:9:
No instance for (RealFrac Integer)
arising from a use of `floor'
Possible fix: add an instance declaration for (RealFrac Integer)
In the first argument of `(.)', namely `floor'
In the expression: (floor . sqrt)
In an equation for `flrt': flrt = (floor . sqrt)
AKS.hs:11:17:
No instance for (Floating Integer)
arising from a use of `sqrt'
Possible fix: add an instance declaration for (Floating Integer)
In the second argument of `(.)', namely `sqrt'
In the expression: (floor . sqrt)
In an equation for `flrt': flrt = (floor . sqrt)
我不明白为什么结果函数不只是Int -> Int。
我刚刚完成了我的第二年计算机科学课程,并完成了基础的PL课程。我听说过类型,但还不太理解。我尝试阅读了一些Haskell教程,但这一切都超出了我的理解范围。
P.S. - 我也不明白Monad是什么。(我的搜索结果中有很多其他问题涉及到这个)
P.P.S. - 我的完整源代码
bar = \a b -> if (2^a) > b
then (a-1)
else bar (a+1) b
foo = bar 1
flrt :: Integer -> Integer
flrt = (floor . sqrt)
aks target = if (target < 2)
then putStr "Not a Prime.\n\n"
else if elem (mod target 10) [0,2,4,5,6,8]
then putStr "Composite\n\n"
else if (elem target) [a^b | a <- [3,5..(flrt target)], b <- [1.. (foo target)]]
then putStr "Composite\n\n"--}
else
putStr "filler"
floor $ sqrt
意味着对函数sqrt
求完平方根后再向下取整。你误将floor
应用于函数sqrt
上了。你需要的是函数复合。尝试使用floor . sqrt
. - Vitusfloor.sqrt
而是想要intSqrt :: Integer -> Integer
(或者实际上是Natural -> Natural
)。sqrt
经过一个不精确的Float
或Double
,考虑到素性测试通常使用非常大的数字,精度损失可能最终会影响您。但是再说一遍,您的算法并不特别适用于大数,所以您也许不用担心 :) - copumpkin