Search code examples
haskelloptparse

Understanding the introductory code snippet for Haskell's popular optparse-applicative library


From an introductory code snippet from the popular optparse library:

data Sample = Sample
  { hello :: String
  , quiet :: Bool }

sample :: Parser Sample
sample = Sample
  <$> strOption -- Q1
      ( long "hello"
     <> metavar "TARGET" -- Q2
     <> help "Target for the greeting" )
  <*> switch
      ( long "quiet"
     <> help "Whether to be quiet" )

See the comments in the code snippet for my questions/confusion.

Q1: How is it that <$> can be used as the first argument of the type constructor Sample? I thought this operation had to be used between a function and a functor.

Q2: What is the operation <> used throughout this code snippet?


Solution

  • Q1: How is it that <$> can be used as the first argument of the type constructor Sample? I thought this operation had to be used between a function and a functor.

    It is the other way around: Sample is the first argument of (<$>), and it is being mapped over the Parser String produced by strOption.

    Q2: What is the operation <> used throughout this code snippet?

    (<>) is a synonym for mappend, from the Monoid class. In this case, it is being used to combine individual settings into the set of settings to be used for each of the command-line options that you are defining.