Skip to content

Commit fa99a5b

Browse files
committed
Offer more specific reader types
1 parent 27387c0 commit fa99a5b

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/Options/Applicative.hs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ module Options.Applicative (
130130

131131
auto,
132132
str,
133+
integral,
134+
numeric,
133135
maybeReader,
134136
eitherReader,
135137
disabled,

src/Options/Applicative/Builder.hs

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ module Options.Applicative.Builder (
5555
-- | A collection of basic 'Option' readers.
5656
auto,
5757
str,
58+
integral,
59+
numeric,
5860
maybeReader,
5961
eitherReader,
6062
disabled,
@@ -118,16 +120,48 @@ import Options.Applicative.Help.Chunk
118120

119121
-- | 'Option' reader based on the 'Read' type class.
120122
auto :: Read a => ReadM a
121-
auto = eitherReader $ \arg -> case reads arg of
122-
[(r, "")] -> return r
123-
_ -> Left $ "cannot parse value `" ++ arg ++ "'"
123+
auto =
124+
eitherReader $ \arg ->
125+
case reads arg of
126+
[(r, "")] ->
127+
return r
128+
_ ->
129+
Left $ "cannot parse value `" ++ arg ++ "'"
130+
124131

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

138+
139+
-- | Integral 'Option' reader.
140+
--
141+
-- Safe ReadM for integral types.
142+
integral :: Integral i => ReadM i
143+
integral =
144+
eitherReader $ \arg ->
145+
case reads arg of
146+
[(r, "")] ->
147+
Right $ fromInteger r
148+
_ ->
149+
Left $ "cannot parse value `" ++ arg ++ "' as integral type"
150+
151+
152+
-- | Numeric 'Option' reader.
153+
--
154+
-- Safe ReadM for numbers.
155+
numeric :: (Read n, Num n) => ReadM n
156+
numeric =
157+
eitherReader $ \arg ->
158+
case reads arg of
159+
[(r, "")] ->
160+
Right r
161+
_ ->
162+
Left $ "cannot parse `" ++ arg ++ "' as a number"
163+
164+
131165
-- | Convert a function producing an 'Either' into a reader.
132166
--
133167
-- As an example, one can create a ReadM from an attoparsec Parser

0 commit comments

Comments
 (0)