Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 863
LennyStackOverflow Avatar asked Oct 01 '10 08:10

LennyStackOverflow


3 Answers

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)

like image 108
Peaker Avatar answered Oct 19 '22 06:10

Peaker


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

like image 43
Neil Brown Avatar answered Oct 19 '22 05:10

Neil Brown


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

like image 3
Daniel Avatar answered Oct 19 '22 06:10

Daniel