"maybe" -like function for Bool and List?

Sometimes I find myself programming a template "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, which are possibly Maybe functions. Whether there is a?

Update: I wanted to use the Bool case as a generalization of a list. For example, when working with Data.Text as T:

if T.null x then x else foo x

I want to reduce this boiler plate code.

+5
source share
3 answers

I think the answer is probably that there is no such general function. As djv says, you can build 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

- , ( , ).

+4

, Maybe.

foldr - .

, : maybe x (const y)

: foldr (const (const y)) x

Bool , :

bool :: a -> a -> Bool -> a
bool t _ True = t
bool _ f False = f
+6

Data.Monoid, , , , , . Bool False List [].

+3

All Articles