“maybe”-like function for Bool and List?
-
27-09-2019 - |
Question
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).
OTHER TIPS
maybe is the catamorphism of the Maybe type.
foldr is the catamorphism of the list type.
If you had used maybe like: maybe x (const y)
You could use: foldr (const (const y)) x
For Bool I also miss the catamorphism in the standard library, but it would be:
bool :: a -> a -> Bool -> a
bool t _ True = t
bool _ f False = f
Check Data.Monoid, it's a typeclass describing data types which have a designated empty value and you can pattern-match on it to write your generic function. There are instances for Bool
with empty value False
and for List
with empty value []
.