AoC 2021 Parsing Arguments

Dated Apr 11, 2022; last modified on Mon, 11 Apr 2022

Parsing the Command Line

lists a couple of libraries. and are the most popular options. Going with as it’s slightly more popular.

{-#  OPTIONS_GHC -Wall  #-}

module AoC2021Args (Args(..), aocArgParser) where

import Options.Applicative
import Data.Semigroup ((<>))

data Args = Args
    { day :: Int }

aocArgParser :: Parser Args
aocArgParser = Args
    <$> option auto
        ( long "day"
       <> help "The day to run code for. Use '0' to run all of the solutions."
       <> showDefault
       <> value 0
       <> metavar "DAY") --  The metavariable is displayed in the help text.

A type a is a Semigroup if it provides an associative function (<>) that lets you combine any two values of type a into one, and the following holds:

(a <> b) <> c == a <> (b <> c)

Found a way of getting the min/max from a list of numbers!

The sconcat function allows us to combine multiple values, e.g. sconcat (1 :| [2, 3, 4]) :: Max Int, which evaluates to Max {getMax = 4}. (1 :| []) is equivalent to [1], but is guaranteed to be non-empty. The sconcat function requires a non-empty list.

With the integration in the main functions of Main and AoC2021Test , I’m able to run code like time cabal run advent-of-code-y2021 -- --day 9.

References

  1. Command line option parsers - HaskellWiki. wiki.haskell.org . Accessed Apr 11, 2022.
  2. optparse-applicative: Utilities and combinators for parsing command line options. hackage.haskell.org . Accessed Apr 11, 2022.
  3. cmdargs: Command line argument processing. hackage.haskell.org . Accessed Apr 11, 2022.
  4. Data.Semigroup. hackage.haskell.org . Accessed Apr 11, 2022.