1

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.

11
  • The monoid structure comes from Max Commented Jul 27, 2016 at 18:38
  • see hackage.haskell.org/package/base-4.9.0.0/docs/src/…. Commented Jul 27, 2016 at 18:42
  • 1
    And Max Commented Jul 27, 2016 at 18:46
  • 3
    (#.) is just an optimized version of the composition operator (.) which only works in some cases, such as in Max . Just. Pretend it's plain composition, and note that Max a is a monoid with binary "max" for its operation (roughly, there's a Maybe wrapper so that we can define the unity to be Nothing). Commented Jul 27, 2016 at 18:46
  • 1
    @jberryman, no you don't. But you need :t (#.), not :t #.. And it's normally imported from Data.Profunctor.Unsafe, but Data.Foldable has its own specialized copy. Commented Jul 27, 2016 at 19:51

1 Answer 1

4

#. is an operator that can make coercions easier to use.

f #. g

means

g, coerced to the type of f . g

Similarly,

f .# g

means

f, coerced to the type of f . g

In most cases, f #. g only makes sense if f is some combination of newtype constructors, newtype accessors, and fmap.

The reason for using #. in maximum us probably over-zealousness on my part. It can almost certainly be replaced with . without any problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.