`mapMaybe`, but once I move from the 'Maybe' monad into something more complex (such as

`ReaderT r Maybe`) things become tricky.

First, what is

`mapMaybe`?

Its type is:

`(a -> Maybe b) -> [a] -> [b]`

It maps the input function over the list, and drops any values which evaluate to nothing. It's like a combination of

`map`and

`filter`, where the input function is given the option to either transform the input or filter it out.

But then I needed more information threaded around in my functions, and the types went from

`a -> Maybe b`to

`a -> ReaderT r Maybe b`.

So I needed:

> mapAlt :: Alternative f => (a -> f b) -> [a] -> f [b]

It's just like

`mapMaybe`, except it works for any Alternative functor.

The output is still in the functor

`f`so I can have it work for effectful monads and such, but it will always return a value (even if it's the empty list).

Here's the implementation:

> mapAlt f xs = go xsLinks:

> where go [] = pure []

> go (y:ys) = (pure (:) <*> f y <*> go ys)

> <|> go ys

Hurrah for simple, useful functions.

## 1 comment:

Holy crap you've been updating this. (This is exciting news to me.)

Post a Comment