"maybe"-like function for Bool and List?
Asked Answered
G

3

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.

Gabrielegabriell answered 1/10, 2010 at 8:50 Comment(1)
Please provide an example on that function for Bool...Weatherly
R
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).

Raman answered 1/10, 2010 at 11:30 Comment(0)
F
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)

Fosque answered 14/10, 2010 at 10:35 Comment(0)
R
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).

Raman answered 1/10, 2010 at 11:30 Comment(0)
L
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 [].

Labyrinth answered 1/10, 2010 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.