Conditional List Building

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.

+6
source share
2 answers

I like to use concat with a list in this case:

 concat [ [a | opt1] , [b | opt2] , [c | opt3] ] 

[a | opt1] [a | opt1] is an empty list if opt1 is False, otherwise it is a singleton list containing only a .

You can also do this with <$ and guard :

 concat [ a <$ guard opt1 , b <$ guard opt2 , c <$ guard opt3 ] 

I do not think that there is onlyIf function onlyIf in the database.

+12
source

You can use Writer (see this question ) and use when instead of Maybe . However, using Maybe instead of a condition, the result might be better.

+2
source

Source: https://habr.com/ru/post/973160/


All Articles