简体   繁体   中英

converting Num to Fractional in Haskell

Basically I have some exercises to learn tuples in Haskell.

In this one I declare a type named StudentMark which requires:

  • A String (the name of the student)
  • Int (the mark of the student, 0 to 100).

Then I have to create a function which caps the mark of a student to a maximum of 40.

But I get this error doing it:

No instance for (Fractional Int) arising from a use of ‘/’

I think it is related with I being returning a double instead of an Int but I cannot figure out how to fix this. Here is the code:

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.

Not exactly, in Haskell, there are no implicit conversions.

Since StudentMark is in fact an alias of (String, Int) that means that mrk is an Int . But your division (/) :: 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

We can thus write this like:

capMark :: StudentMark -> StudentMark
capMark (std, mrk) = (std,  (mrk * 4) )

or a shorter version with second :: Arrow a => abc -> a (d, b) (d, c) :



capMark :: StudentMark -> StudentMark
capMark = second ((`div` 10) . (*4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM