% Applicative Parsing % Julie Moronuki % January 10, 2017
fmap :: (a -> b) -> f a -> f b
-
... is a kind of functor.
-
but the
(a -> b)
offmap
has become an(a -> f b)
fmap :: Functor f => (a -> b) -> f a -> f b
(>>=) :: Monad m => m a -> (a -> m b) -> m b
fmap :: Functor f => (a -> b) -> f a -> f b
(=<<) :: Monad m => (a -> m b) -> m a -> m b
join :: Monad m => m (m a) -> m a
Pray I do not alter it further.
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
- context sensitivity
- composability (applicatives compose; monads need transformers)
doSomething = do
a <- f
b <- g
c <- h
pure (a, b, c)
doSomething' n = do
a <- f n
b <- g a
c <- h b
pure (a, b, c)
- like an Either, but accumulates error values
- cannot have a Monad instance
- language extension
- allows use of
do
syntax with applicatives
In this hour, we'll be working on a small project with the optparse-applicative library.
-- stack new optex simple
Here are some basic argument types we can use: commands, flags, switches.
command :: String -> ParserInfo a -> Mod CommandFields a
Add a command to a subparser option.
flag :: a -> a -> Mod FlagFields a -> Parser a
-- [1] [2] [3] [4]
-
default value
-
active value
-
option modifier
-
Builder for a flag parser
switch :: Mod FlagFields Bool -> Parser Bool
-- flagEx.hs
subparser :: Mod CommandFields a -> Parser a
-- Builder for a command parser.
strArgument :: Mod ArgumentFields String -> Parser String
-- Builder for a String argument.
argument :: ReadM a -> Mod ArgumentFields a -> Parser a
-- Builder for an argument parser.
short :: HasName f => Char -> Mod f a
-- Specify a short name for an option.
long :: HasName f => String -> Mod f a
-- Specify a long name for an option.
metavar :: HasMetavar f => String -> Mod f a
-- Specify a metavariable for the argument.
execParser :: ParserInfo a -> IO a
Run a program description.
Parse command line arguments. Display help text and exit if any parse error occurs.