Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard Haskell function :: (a -> Maybe b) -> [a] -> Maybe b

Tags:

haskell

There is a standard tryPick function if F# that returns the first (from left-to-right if any at all) successful application of a function on an element of a list. I am hopping there is a standard function like that in Haskell. I tried Hoogle and didn't find anything.

I am new to Haskell and I am not sure what the right way of doing it is. Would you do it like this:

tryPick:: (a -> Maybe b) -> [a] -> Maybe b
tryPick try xs = case Maybe.mapMaybe try xs of
    [] -> Nothing
    (x:_) -> Just x

?

like image 312
Trident D'Gao Avatar asked Oct 28 '13 19:10

Trident D'Gao


People also ask

What does maybe mean in Haskell?

The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a ), or it is empty (represented as Nothing ). Using Maybe is a good way to deal with errors or exceptional cases without resorting to drastic measures such as error .

What is left and right in Haskell?

The Either type is sometimes used to represent a value which is either correct or an error; by convention, the Left constructor is used to hold an error value and the Right constructor is used to hold a correct value (mnemonic: "right" also means "correct").


1 Answers

You want:

tryPick :: (a -> Maybe b) -> [a] -> Maybe b
tryPick f as = msum (map f as)

I'll explain how this works.

map f as produces a list of possible Maybe actions to try:

map f as :: [Maybe b]

msum tries them sequentially until one succeeds (returning the value as a Just) or they all fail (returning a Nothing). For example:

> msum [Nothing, Just 2, Just 3, Nothing]
Just 2
> msum [Nothing, Nothing]
Nothing

Note that msum's type is more general, so we can generalize the signature to:

tryPick :: (MonadPlus m) => (a -> m b) -> [a] -> m b

This will now work for any MonadPlus. Have fun discovering what it does for other MonadPlus types.

like image 117
Gabriella Gonzalez Avatar answered Sep 20 '22 16:09

Gabriella Gonzalez