Question

I have few command-line options (5 for example) and I want to convert them to tuple. The problem is that I expect them to appear in correct order, so tuple can be easily built from list using pattern-match, but in real life options can be provided in random order, so I don't know if head of the list contain Verbose option or log file name?

I tried to think how to do that using continuation-passing style, however nothing useful comes into my mind.

Is that ever possible?

I think that I can "sort" the list to have it in predicted order, but it does not look good.

Also I could get rid of the tuple and create data record - however that will still lead up to checking the type of attribute and set the correct field of the record. Still a lot of typing.

Was it helpful?

Solution

Given what you describe, I think you have two options. Of the two, I would say that converting to a dictionary would be easiest, but converting to a Tuple would work and only be a little clumsy

So, take this definition:

options :: [OptDescr (String, String)]
options = [Option ['a'] ["alpha"] (ReqArg (\a -> ("alpha", a)) "empty") "",
           Option ['b'] ["beta"] (ReqArg (\a -> ("beta", a)) "empty") "",
           Option ['g'] ["gamma"] (ReqArg (\a -> ("gamma", a)) "empty") ""]

main = do
    args <- getArgs
    let (opts, nonopts, errs) = getOpt Permute options args
    putStrLn $ show opts

From this, a couple of my example outputs are:

[("beta","b"),("alpha","a")]
[("alpha","a"),("gamma","g"),("beta","b")]

and so on. Same order as on the command line. But, because of the way I set it up above, I basically have an association list, so... if I in particular want a Tuple that has the values (alpha, beta, gamma), then my best option is...

(lookup "alpha" opts, lookup "beta" opts, lookup "gamma" opts)

You resulting data type would be (Maybe String, Maybe String, Maybe String), in the order of "alpha", "beta", and "gamma".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top