Why is the haskell function not working correctly?

65 views Asked by At

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.

1

There are 1 answers

1
willeM_ Van Onsem On BEST ANSWER

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