Creating the getopt function

This commit is contained in:
Zoe Roux
2021-03-10 16:55:39 +01:00
parent cca9d9bd4f
commit 9b78c23a11
3 changed files with 22 additions and 4 deletions
+17 -1
View File
@@ -3,4 +3,20 @@ module GetOpt where
import GetOpt.Data
import GetOpt.Options
import GetOpt.Parsers
import GetOpt.Parsers
getOpt :: Parser a -> [String] -> Maybe (a, [String])
getOpt (DefParser a) args = Just (a, args)
getOpt p args = case runParser p args of
Just (p1, args1) -> getOpt p1 args1
Nothing -> Nothing
where
runParser :: Parser a -> [String] -> Maybe (Parser a, [String])
runParser (OptParser opt next) (identifier:arg:args)
| optionMatch opt identifier = do
ret <- parser opt arg
return (fmap ret next, args)
| otherwise = do
(nextP, newArgs) <- runParser next (identifier:args)
return (OptParser opt nextP, newArgs)
runParser p@(DefParser _) args = Just (p, args)
-2
View File
@@ -10,8 +10,6 @@ data Parser a where
DefParser :: a -> Parser a
OptParser :: Option (a -> b) -> Parser a -> Parser b
-- newtype OptionParser a = OptionParser { parse :: String -> Maybe a }
type OptionParser a = (String -> Maybe a)
data Option a = Option {
+5 -1
View File
@@ -31,4 +31,8 @@ instance Semigroup (Mod a) where
option :: OptionParser a -> Mod a -> Parser a
option p (Mod m) = OptParser (fmap const (m $ def p)) (DefParser ())
where
def = Option "VAR" "" ' ' Nothing "No help message set."
def = Option "VAR" "" ' ' Nothing "No help message set."
optionMatch :: Option a -> String -> Bool
optionMatch opt [d, s] = d == '-' && s == shortName opt
optionMatch opt (d:d1:l) = d == '-' && d1 == '-' && l == longName opt