5

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.

1
  • 1
    Please provide an example on that function for Bool...
    – kennytm
    Oct 1, 2010 at 9:01

3 Answers 3

7

maybe is the catamorphism of the Maybe type.

foldr is the catamorphism of the list type.

Data.Bool.bool is the catamorphism of the Bool type.

If you had used maybe like: maybe x (const y)

You could use: foldr (const (const y)) x

Your example if T.null x then x else foo x could be written with bool as

bool foo id (T.null x) x

(it takes the False case first, the opposite of if)

0
4

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).

3

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 [].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.