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
?
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 .
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").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With