Blog Archive

Saturday, June 21, 2008

Haskell Snippets

I'm a huge fan of the function 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 xs
> where go [] = pure []
> go (y:ys) = (pure (:) <*> f y <*> go ys)
> <|> go ys
Links:
Hurrah for simple, useful functions.

1 comment:

Gordon said...

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

Listening:

Watching:

  • House
  • Ride Back