From 9b78c23a11a87991c256b8cf69fe247ff6a74609 Mon Sep 17 00:00:00 2001 From: Zoe Roux Date: Wed, 10 Mar 2021 16:55:39 +0100 Subject: [PATCH] Creating the getopt function --- GetOpt.hs | 18 +++++++++++++++++- GetOpt/Data.hs | 2 -- GetOpt/Options.hs | 6 +++++- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/GetOpt.hs b/GetOpt.hs index f4a89ba..c9da916 100644 --- a/GetOpt.hs +++ b/GetOpt.hs @@ -3,4 +3,20 @@ module GetOpt where import GetOpt.Data import GetOpt.Options -import GetOpt.Parsers \ No newline at end of file +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) \ No newline at end of file diff --git a/GetOpt/Data.hs b/GetOpt/Data.hs index 23ed1b1..858f986 100644 --- a/GetOpt/Data.hs +++ b/GetOpt/Data.hs @@ -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 { diff --git a/GetOpt/Options.hs b/GetOpt/Options.hs index 373262c..737a03f 100644 --- a/GetOpt/Options.hs +++ b/GetOpt/Options.hs @@ -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." \ No newline at end of file + 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 \ No newline at end of file