Search code examples
haskellcatamorphism

"maybe"-like function for Bool and List?


Sometimes i find myself progamming the pattern "if the Bool is not false" or "if the list is not empty use it, otherwise use something else".

I am looking for functions for Bool and List that are what the "maybe" function is to Maybe. Are there any?

Update: I meant to use the Bool-case as a generalization of the List-case. For example when working with Data.Text as T:

if T.null x then x else foo x

I am looking to reduce such boiler plate code.


Solution

  • I think the answer is probably that there isn't such a generic function. As djv says, you can perhaps build on Data.Monoid to write one, something like:

    maybe' :: (Eq a, Monoid a) => b -> (a -> b) -> a -> b
    maybe' repl f x = if x == mempty then repl else f x
    

    But I don't know of any functions in the standard library like that (or any that could easily be composed together to do so).