【发布时间】:2019-02-13 03:04:09
【问题描述】:
基本上我有一些练习来学习 Haskell 中的元组。
在这个我声明了一个名为 StudentMark 的类型,它需要:
- 字符串(学生姓名)
- Int(学生的分数,0 到 100)。
然后我必须创建一个函数,将学生的分数上限限制为 40。
但我这样做会出错:
No instance for (Fractional Int) arising from a use of ‘/’
我认为这与我返回一个 double 而不是 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))
【问题讨论】:
-
因为
StudentMark是String和Int的元组,这在这里似乎没有多大意义。您实际上应该将其转换回Int,或者将其保留为Int,例如(std, div (mrk * 4) 10)。