packages feed

papa-0.7.0: src/Papa/Base/Text/Read.hs

{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | Total parsing of 'Prelude.Show'n values.
--
-- @read@ is not exported: it is partial. The 'Read' class is exported, so
-- that its constraint can be written, but not its methods. Do not write
-- 'Read' instances; use a parser library for anything that is not the
-- output of 'Prelude.show'.
module Papa.Base.Text.Read (
  module P,
  readIO,
) where

import Control.Applicative (pure)
import Control.Category ((.))
import Data.Maybe (Maybe)
import Data.String (String)
import Text.Read as P (
  Read,
  readEither,
  readMaybe,
  reads,
 )
import Prelude (IO)

-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> import Papa hiding (readEither, readIO, readMaybe)
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range

-- | Total 'Prelude.readIO': 'Data.Maybe.Nothing' for a string that does not parse,
-- where "Prelude"'s @readIO@ throws an 'Prelude.IOError'.
--
-- ==== __Examples__
--
-- >>> readIO "42" :: IO (Maybe Int)
-- Just 42
--
-- >>> readIO "forty-two" :: IO (Maybe Int)
-- Nothing
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int Range.linearBounded); r <- evalIO (readIO (show n)); r === Just n
-- ...passed 100 tests.
-- True
--
-- @since 0.6.0
readIO :: (Read a) => String -> IO (Maybe a)
readIO =
  pure . readMaybe
{-# INLINE readIO #-}