How Long is your List?

Posted on January 15, 2022 by Jack Kelly
Tags: haskell, coding

Quite a few of my favourite Haskell idioms involve the Foldable instance for Maybe:

-- This is reimplemented all over the place as `whenJust`.
-- Pass our `a` to the function, if we have one,
-- and ignore its result; return `pure ()` otherwise.
for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
for_ @Maybe :: Applicative f => Maybe a -> (a -> f b) -> f ()

-- Equivalent to `Data.Maybe.fromMaybe mempty`:
-- Return the `m` if we have one; otherwise, return `mempty`.
fold :: (Foldable t, Monoid m) => t m -> m
fold @Maybe :: Monoid m => Maybe m -> m

-- Equivalent to `maybe mempty`:
-- Pass our `a` to our function, if we have one;
-- otherwise, return `mempty`.
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m
foldMap @Maybe :: Monoid m => (a -> m) -> Maybe a -> m

Some of these confuse people more than I think they should, so this post aims to help with that. Instead of looking at Maybe a as “just-a-or-nothing”, the key is to become comfortable with Maybe as “list of zero or one elements”. We’ll also go looking for other types which can be seen as “lists of some number of elements”.

Read more...

Someone Might Have Asked for This

Posted on January 14, 2022 by Jack Kelly
Tags: wiki, haskell

I’ve run across a lot of extremely good Haskell resources over the years, and there are a few that I refer to over and over again when teaching. Instead of relying on my memory and hoping to recall the right talks in response to the right questions, I’ve collected the best of them on a wiki page. Hopefully it’s useful.

All Posts | RSS | Atom
Copyright © 2024 Jack Kelly
Site generated by Hakyll (source)