在 Haskell 中将数字转换为分数
converting Num to Fractional in Haskell
基本上我在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))
I think it is related with I being returning a double instead of an Int but I cannot figure out how to fix this.
不完全是,在 Haskell 中没有隐式转换。
因为 StudentMark
实际上是 (String, Int)
的别名,这意味着 mrk
是 Int
。但是你的师(/) :: Fractional a => a -> a -> a
takes as type a Fractional a
, and an Int
is not a member of the Fractional
typeclass. For integral divisions, one can use div :: Integral a => a -> a -> a
因此我们可以这样写:
capMark :: StudentMark -> StudentMark
capMark (std, mrk) = (std, <b>div</b> (mrk * 4) <b>10</b>)
或更短的版本 second :: Arrow a => a b c -> a (d, b) (d, c)
:
<b>import Control.Arrow(second)</b>
capMark :: StudentMark -> StudentMark
capMark = second ((`div` 10) . (*4))
基本上我在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))
I think it is related with I being returning a double instead of an Int but I cannot figure out how to fix this.
不完全是,在 Haskell 中没有隐式转换。
因为 StudentMark
实际上是 (String, Int)
的别名,这意味着 mrk
是 Int
。但是你的师(/) :: Fractional a => a -> a -> a
takes as type a Fractional a
, and an Int
is not a member of the Fractional
typeclass. For integral divisions, one can use div :: Integral a => a -> a -> a
因此我们可以这样写:
capMark :: StudentMark -> StudentMark
capMark (std, mrk) = (std, <b>div</b> (mrk * 4) <b>10</b>)
或更短的版本 second :: Arrow a => a b c -> a (d, b) (d, c)
:
<b>import Control.Arrow(second)</b>
capMark :: StudentMark -> StudentMark
capMark = second ((`div` 10) . (*4))