4

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

laiboonh
  • 1,377
  • 1
  • 9
  • 19
  • [isNaN](http://hackage.haskell.org/package/base-4.6.0.1/docs/Prelude.html#v:isNaN) – user2407038 Nov 22 '17 at 05:37
  • Just for context or if you want to read more about this, the behavior you're asking about isn't specific to haskell but is an aspect of the IEEE 754 floating point standard – jberryman Nov 22 '17 at 17:17

1 Answers1

7

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)
Alec
  • 31,829
  • 7
  • 67
  • 114
  • Thanks for the answer and pointing out the problems. Yeah i was just trying to illustrate my doubts quickly. – laiboonh Nov 22 '17 at 06:16
  • @laiboonh I figured. :) – Alec Nov 22 '17 at 06:18
  • 2
    Instead of using `fromIntegral` here, it would usually make more sense to adjust the argument types to be floating point. Coercing with `fromIntegral` yourself prevents the user from choosing a type, *and* forces GHC to use defaulting rules, which are a bit weird. – amalloy Nov 22 '17 at 06:39
  • What *is* `Infinity`, though? Hard-coded representation of IEEE infinity? – chepner Nov 22 '17 at 16:11
  • 1
    @chepner in the case of `Float` at least, looks like `Infinity` is the representation of numbers that satisfy `isInfinite` and `> 0` – Alec Nov 22 '17 at 16:25