基本上我有一些练习来学习Haskell中的元组。
在这个我声明一个名为StudentMark的类型,它需要:
然后我必须创建一个功能,将学生的标记限制为最多40。
但我得到这个错误:
No instance for (Fractional Int) arising from a use of ‘/’
我认为这与我返回一个双重而不是一个Int有关,但我无法弄清楚如何解决这个问题。这是代码:
import Data.Char
type StudentMark = (String, Int)
{- the total mark without cap would be 100, with the cap it would be 40,
if we divide 100/40 we get 2.5 which is a common factor
-}
capMark :: StudentMark -> StudentMark
capMark (std, mrk) = (std, fromIntegral (mrk / 2.5))
我认为这与我返回一个双重而不是一个Int有关,但我无法弄清楚如何解决这个问题。
不完全是,在Haskell中,没有隐式转换。
由于StudentMark
实际上是(String, Int)
的别名,这意味着mrk
是Int
。但你的分区(/) :: Fractional a => a -> a -> a
采用Fractional a
类型,而Int
不是Fractional
类型类的成员。对于整体划分,可以使用div :: Integral a => a -> a -> a
我们可以这样写:
capMark :: StudentMark -> StudentMark
capMark (std, mrk) = (std, div (mrk * 4) 10)
或second :: Arrow a => a b c -> a (d, b) (d, c)
的较短版本:
import Control.Arrow(second)
capMark :: StudentMark -> StudentMark
capMark = second ((`div` 10) . (*4))