Home > Software design >  Fractional type with Maybe
Fractional type with Maybe

Time:11-15

What is wrong with the type of ( x / y ) ?

my :: (Integral a, Fractional b) =>  a -> a -> Maybe b            
my x y
 | y == 0 = Nothing
 | otherwise = Just ( x / y )

CodePudding user response:

The (/) :: Fractional a => a -> a -> a requires that the two operands and the return type are all the same. This thus means that your my should be written as:

my :: (Eq a, Fractional a) => a -> a -> Maybe a
my _ 0 = Nothing
my x y = Just (x / y)

Another option is to work with (%) :: Integral a => a -> a -> Ratio a and fromRational :: Fractional a => Rational -> a:

import Data.Ratio((%))

my :: (Integral a, Fractional b) => a -> a -> Maybe b
my _ 0 = Nothing
my x y = Just (fromRational (fromIntegral x % fromIntegral y))
  • Related