I was just looking up the implementation of the maximum function in haskell:
maximum :: forall a . Ord a => t a -> a
maximum = fromMaybe (errorWithoutStackTrace "maximum: empty structure") .
getMax . foldMap (Max #. (Just :: a -> Maybe a))
Could somebody explain this piece of code to me?
In particular it is not clear to me how this part
Max #. (Just :: a -> Maybe a)
works. What does #. mean? To me it looks like something similar to function composition but typing
:t #.
in the REPL gives an error. Also I think the argument for foldMap should be of the form
Monoid m => a -> m
But I can't see where the monoid structure comes from here.
Max(#.)is just an optimized version of the composition operator(.)which only works in some cases, such as inMax . Just. Pretend it's plain composition, and note thatMax ais a monoid with binary "max" for its operation (roughly, there's aMaybewrapper so that we can define the unity to beNothing).:t (#.), not:t #.. And it's normally imported fromData.Profunctor.Unsafe, butData.Foldablehas its own specialized copy.