Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Offer more specific reader types #364

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Options/Applicative.hs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ module Options.Applicative (

auto,
str,
integral,
numeric,
maybeReader,
eitherReader,
disabled,
Expand Down
40 changes: 37 additions & 3 deletions src/Options/Applicative/Builder.hs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ module Options.Applicative.Builder (
-- | A collection of basic 'Option' readers.
auto,
str,
integral,
numeric,
maybeReader,
eitherReader,
disabled,
Expand Down Expand Up @@ -118,16 +120,48 @@ import Options.Applicative.Help.Chunk

-- | 'Option' reader based on the 'Read' type class.
auto :: Read a => ReadM a
auto = eitherReader $ \arg -> case reads arg of
[(r, "")] -> return r
_ -> Left $ "cannot parse value `" ++ arg ++ "'"
auto =
eitherReader $ \arg ->
case reads arg of
[(r, "")] ->
return r
_ ->
Left $ "cannot parse value `" ++ arg ++ "'"


-- | String 'Option' reader.
--
-- Polymorphic over the `IsString` type class since 0.14.
str :: IsString s => ReadM s
str = fromString <$> readerAsk


-- | Integral 'Option' reader.
--
-- Safe ReadM for integral types.
integral :: Integral i => ReadM i
integral =
eitherReader $ \arg ->
case reads arg of
[(r, "")] ->
Right $ fromInteger r
_ ->
Left $ "cannot parse value `" ++ arg ++ "' as integral type"


-- | Numeric 'Option' reader.
--
-- Safe ReadM for numbers.
numeric :: (Read n, Num n) => ReadM n
numeric =
eitherReader $ \arg ->
case reads arg of
[(r, "")] ->
Right r
_ ->
Left $ "cannot parse `" ++ arg ++ "' as a number"


-- | Convert a function producing an 'Either' into a reader.
--
-- As an example, one can create a ReadM from an attoparsec Parser
Expand Down