gpt4 book ai didi

haskell - truncate::(RealFrac a, Integral b) => a -> b 的问题

转载 作者:行者123 更新时间:2023-12-05 08:44:32 29 4
gpt4 key购买 nike

我正在玩 lagrest prime divisor 并且我在使用这段代码时遇到了麻烦:

lpd :: Integer -> Integer
lpd n = helper n (2:[3,5..ceiling])
where
helper n divisors@(d:ds)
| n == d = n
| n `rem` d == 0 = helper (n `div` d) divisors
| otherwise = helper n ds
ceiling = truncate $ sqrt n

错误信息是:

problems.hs:52:15:
No instance for (RealFrac Integer)
arising from a use of `truncate'
Possible fix: add an instance declaration for (RealFrac Integer)
In the expression: truncate
In the expression: truncate $ sqrt n
In an equation for `ceiling': ceiling = truncate $ sqrt n

problems.hs:52:26:
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 n'
In the expression: truncate $ sqrt n
In an equation for `ceiling': ceiling = truncate $ sqrt n
Failed, modules loaded: none.

看来我的打字有欠缺。我该怎么做才能使这段代码正常工作?

最佳答案

sqrt n 替换为 sqrt $ fromIntegral n

问题是 sqrt 的类型是 (Floating a) => a -> a,所以它不适用于整数。功能

fromIntegral :: (Integral a, Num b) => a -> b

从整数类型“转换”为更一般的 Num 实例。

关于haskell - truncate::(RealFrac a, Integral b) => a -> b 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7739598/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com