Errors and exceptions in Haskell

So the type signature says more than it does in most languages, and consequently, the reason a Haskeller might leave this lookup function undocumented, or very, very sparsely documented, is that

 lookup :: Eq a => a -> [(a,b)] -> Maybe b

only describes one sensible function, from a human point of view. It is obviously comparing the a you pass in to the a in the tuples and returning either the first thing it finds as a Just a or Nothing if it finds nothing.

Nitpick: there is more than one sensible function here. You single out the one that returns the second value from the first matching pair, but there's for example also the one that returns the second value from the last matching pair. I'm not a beginner, so the first way I think of to write that second function is somewhat intermediate:

import Data.Foldable (foldMap)
import Data.Monoid (Last(..))

lookupLast :: Eq k => k -> [(k, v)] -> Maybe v
lookupLast k = getLast . foldMap step
  where step (k', v)
            | k == k'   = Last (Just v)
            | otherwise = Last 

Basically:

  1. The standard foldMap function is a simple version of what people these days call "map/reduce", which combines two things:
    • The "mapper": apply a function to every element of the input collection.
    • The "reducer": use some rule to combine the resulting elements into one summary value.
  2. The Last type is a monoid (reducer strategy) that chooses later values over earlier ones;
  3. So my "mapper" here does this:
    • Turn pairs with the same key as k into Just v;
    • Wrap them with Last to tell the "reducer" to prefer the last ones.
/r/programming Thread Parent Link - stackbuilders.com