haskellfractions

Why is the haskell function not working correctly?


I am wondering which mistake the following Haskellcode has!

f :: Fractional a => a -> a -> a
f x y
 | x > y = x - y
 | otherwise = x + y
call = f 3.5 2.0

I was trying to solve the problem but I couldnt find a solution since 3.5 and 2.0 are floats and that should work with the fractional type.


Solution

  • Well you are comparing the two items x and y, and this is not exported by the Fractional typeclass or any of its superclasses, you need to make constrain it to Ord as well:

    f :: (Ord a, Fractional a) => a -> a -> a
    f x y
       | x > y = x - y
       | otherwise = x + y

    Float, Double, etc. are all instances of Ord so we can compare the values, so then we get:

    ghci> f 3.5 2.0
    1.5