title: How can I detect zero denominator when reading Ratios?
body: <p>I want to read a Ratio from a String, but I don't want my program to crash when the denominator is zero. How can I detect a zero denominator and avoid an error? Just using <code>readMaybe</code> doesn't work:</p>
  <pre><code>Prelude Text.Read&gt; readMaybe &quot;1 % 0&quot; :: Maybe Rational
  Just *** Exception: Ratio has zero denominator
  </code></pre>
  <p>I created this far from perfect solution:</p>
  <pre><code>readMaybeRational :: String -&gt; Maybe Rational
  readMaybeRational s =
    case ((readMaybe $ drop 1 $ dropWhile (/='%') s) :: Maybe Int)
      of Just 0 -&gt; Nothing
         _ -&gt; readMaybe s
  </code></pre>
  <p>But I don't know how to handle a nested Ratio nicely:</p>
  <pre><code>&quot;Just (1 % 0)&quot;
  </code></pre>
  <p>If I could override Ratio's Read instance, I could get readMaybe to return Nothing when the denominator is zero:</p>
  <pre><code>instance (Integral a, Read a) =&gt; Read (Ratio a) where
    readPrec =
      parens
      ( prec ratioPrec
        ( do x &lt;- step readPrec
             expectP (L.Symbol &quot;%&quot;)
             y &lt;- step readPrec
             -- is y 0? If so, do something here
             return (x % y)
        )
      )
  </code></pre>
  <p>But I'm pretty sure I can't do that.</p>