I want to build a list of command line arguments from a group of other predefined variables in Haskell. Like the nature of many command line options, they are either present or not.
Is there a common idiom for conditional list building in Haskell? The if-then-else approach seems rather tedious:
import Control.Monad join [ if opt1 then [a] else [] , if opt2 then [b] else [] , if opt3 then [c] else [] ] -- gives me back [a, c] or something like that.
I have something like
onlyIf :: MonadPlus m => a -> Bool -> ma onlyIf ap = if p then return a else mzero
or
mwhen :: Monoid a => Bool -> a -> a mwhen pa = if p then a else mempty
which could then be used as
a `onlyIf` opt1 <> b `onlyIf` opt2 <> c `onlyIf` opt3
or
mwhen opt1 [a] <> mwhen opt2 [b] <> mwhen opt3 [c]
Hoogle is not very useful here, and of course, there may be a much better (or more general) way to do this.
source share