在Haskell中将Number转换为Fractional

问题描述 投票:1回答:1

基本上我有一些练习来学习Haskell中的元组。

在这个我声明一个名为StudentMark的类型,它需要:

  • 一个字符串(学生的名字)
  • Int(学生的标记,0到100)。

然后我必须创建一个功能,将学生的标记限制为最多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))
haskell int tuples double
1个回答
2
投票

我认为这与我返回一个双重而不是一个Int有关,但我无法弄清楚如何解决这个问题。

不完全是,在Haskell中,没有隐式转换。

由于StudentMark实际上是(String, Int)的别名,这意味着mrkInt。但你的分区(/) :: 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))
© www.soinside.com 2019 - 2024. All rights reserved.