How can we make use of `Infinity` that Haskell returns when you do `2/0`

Viewed 516

I understand that Haskell tries to do something more beneficial than simply throwing an error when one does division by zero

test :: Int -> Int -> String
test a b = case a/b of
    Infinity -> "fool"
    x  -> Show x

However i was told my ghc that Infinity is not a data constructor. What is it actually and how can i make use of it? I don't want to simply check b for 0

1 Answers

There are a handful of ways to do this. My preferred one would be to use isInfinite from the Prelude:

test :: Int -> Int -> String
test a b = case fromIntegral a / fromIntegral b of
             x | isInfinite x && x > 0 -> "fool"
               | otherwise -> show x

Alternately, you could define infinity as in this question and compare for equality (since Infinity == Infinity).


Your code also had a couple of issues I assume are unrelated to your question:

  • Show should be show
  • (/) doesn't work for Int arguments, so you need to use fromIntegral to convert a and b to something floating

I also suspect you aware this particular function doesn't require an infinity check...

test :: Int -> Int -> String
test a 0 | a > 0 = "fool"
         | otherwise = show (fromIntegral a / fromIntegral b)
Related