Haskell递归(由于使用‘;round’;)而产生的(RealFrac Int)没有实例)
在Haskell递归(由于使用‘;round’;)而产生的(RealFrac Int)没有实例),haskell,recursion,Haskell,Recursion,在halfy=round(y/2)中,您有y::Int。但是,(/)运算符是在分数类型类中定义的(该Int不是的一个实例;请考虑哪个Int可以表示,例如3/2) 但是,也有一些函数将为您提供四舍五入的,Int结果。因此,只需将halfy的定义替换为 Recursion.hs:39:19: No instance for (RealFrac Int) arising from a use of ‘round’ In the expression: round (y / 2)
halfy=round(y/2)
中,您有y::Int
。但是,(/)
运算符是在分数类型类中定义的(该Int
不是的一个实例;请考虑哪个Int
可以表示,例如3/2
)
但是,也有一些函数将为您提供四舍五入的,Int
结果。因此,只需将halfy
的定义替换为
Recursion.hs:39:19:
No instance for (RealFrac Int) arising from a use of ‘round’
In the expression: round (y / 2)
In an equation for ‘halfy’: halfy = round (y / 2)
In an equation for ‘modPow’:
modPow x y n
| even y = (((x ^ halfy) `mod` n) ^ 2) `mod` n
| otherwise = (x `mod` n) * (x ^ (y - 1) `mod` n) `mod` n
where
halfy = round (y / 2)
Recursion.hs:39:27:
No instance for (Fractional Int) arising from a use of ‘/’
In the first argument of ‘round’, namely ‘(y / 2)’
In the expression: round (y / 2)
In an equation for ‘halfy’: halfy = round (y / 2)
这将恢复您的halfy
行为,因为暂时忘记键入问题,y/2
的分数部分始终为0或0.5,并且round
两个回合都朝着0:
halfy = y `quot` 2
除法运算符的类型为分数a=>a->a->a
(您可以通过在GHCi中运行:t(/)
自行检查)。但是,Int
不是fractive
类型类的实例。
halfy = y `quot` 2
Prelude> round (1/2) :: Int
0
Prelude> round (-1/2) :: Int
0
Prelude> 1 `quot` 2 :: Int
0
Prelude> (-1) `quot` 2 :: Int
0
Prelude> (-1) `div` 2 :: Int -- This doesn't recover the same behaviour for negative y!
-1