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
orNothing
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:
foldMap
function is a simple version of what people these days call "map/reduce", which combines two things:
Last
type is a monoid (reducer strategy) that chooses later values over earlier ones;k
into Just v
;Last
to tell the "reducer" to prefer the last ones.