我如何划分 haskell 然后 return 在列表中回答
How do i divide in haskell and then return answer in a list
大家好,我是 Haskell 的新手,想知道是否有人可以教我除法以及为什么我的代码不起作用。任何 help/crit 表示赞赏
grades :: Int -> Int -> Int -> Int -> [Int]
grades a x y z =[(fromIntegral(a-x) / fromIntegral (x)) * fromIntegral(100)]
我希望我的代码计算从 x 到 a 的百分比增加,然后 return 它在列表中。
错误:
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,2,4,4,6,6,8,8,10,10]
函数都是RealFrac
class的方法:
> :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]
大家好,我是 Haskell 的新手,想知道是否有人可以教我除法以及为什么我的代码不起作用。任何 help/crit 表示赞赏
grades :: Int -> Int -> Int -> Int -> [Int]
grades a x y z =[(fromIntegral(a-x) / fromIntegral (x)) * fromIntegral(100)]
我希望我的代码计算从 x 到 a 的百分比增加,然后 return 它在列表中。
错误:
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,2,4,4,6,6,8,8,10,10]
函数都是RealFrac
class的方法:
> :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]