问题描述
嗨,我是 Haskell 的新手,想知道是否有人可以教我除法以及为什么我的代码不起作用。感谢任何帮助/暴击
grades :: Int -> Int -> Int -> Int -> [Int]
grades a x y z =[(fromIntegral(a-x) / fromIntegral (x)) * fromIntegral(100)]
我希望我的代码计算从 x 到 a 的百分比增加,然后在列表中返回它。
错误:
No instance for (Fractional Int) arising from a use of `/'
* In the first argument of `(*)',namely
`(fromIntegral (a - x) / fromIntegral (x))'
In the expression:
(fromIntegral (a - x) / fromIntegral (x)) * fromIntegral (100)
In the expression:
[(fromIntegral (a - x) / fromIntegral (x)) * fromIntegral (100)]
解决方法
您的类型签名给出的结果类型为 [Int]
,但除法 (/) :: Fractional a => a -> a -> a
的结果是 Fractional
类型,而 Int
不是,因为错误告诉我们:
No instance for (Fractional Int) arising from a use of `/'
您可以使用例如解决此问题round
:
grades :: Int -> Int -> Int -> Int -> [Int]
grades a x y z = [round $ (fromIntegral(a-x) / fromIntegral (x)) * fromIntegral(100)]
其他可能性是 floor
或 ceiling
,以获得更“可预测”的行为。 round
使用银行家的四舍五入:
> map round [0.5..10]
[0,2,4,6,8,10,10]
函数都是RealFrac
类的方法:
> :i RealFrac
class (Real a,Fractional a) => RealFrac a where
properFraction :: Integral b => a -> (b,a)
truncate :: Integral b => a -> b
round :: Integral b => a -> b
ceiling :: Integral b => a -> b
floor :: Integral b => a -> b
或者,如果您希望成绩更精确,您可以更改类型签名而根本不更改您的代码:
grades :: Int -> Int -> Int -> Int -> [Float]