0

How can I implement a non empty string argument?

parserStart :: Parser String
parser = strArgument (metavar "EXAMPLE") 

How can prevent it from successfully parsing an empty string - ""?

Having previous experience with Parsec/Attoparsec, I assume I could write my own parser or possibly use something applicative to inspect the value and fail if it's an empty string (I think this won't be possible as I need a Monad for this)?

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286

1 Answers1

1
import Data.String
import Data.Text
import Options.Applicative.Types (ReadM, readerAsk)

nonEmptystr :: IsString s => ReadM s
nonEmptystr = do
  readerAsk >>= \case
    "" -> fail "Invalid argument: Empty string"
    x -> pure $ fromString x

f :: Parser Text
f = argument nonEmptystr (metavar "task") 
Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
  • 1
    I usually write these things with `Options.Applicative.eitherReader`, which is a small wrapper for this pattern of binding the result of `readerAsk` and calling `fail` or `return` accordingly: `nonEmptyStr = eitherReader \case { "" -> Left "…"; x -> Right $ fromString x }` (with `BlockArguments` too) – Jon Purdy Apr 23 '19 at 01:28