9

The composition of f and g that looks like

f :. g = \a b -> f (g a) (g b)

is a pattern I find very often in my code. It is similar to unary function composition, only f is binary and I want g applied to both arguments before they are passed to f.

When I ask lambdabot to convert this to point-free form, I get the weird incantation

flip ((.) . f . g) g

which I'd rather not have in my code, so I end up just writing out the pattern explicitly.

Is there a commonly accepted way of writing a combinator for this situation? Or am I weird for finding myself in this situation quite a lot?

I don't have an actual example of when I use this on hand right now since I have never thought to ask here when I've needed it, but one could imagine writing the euclidean distance formula very neatly with it, like so:

distance = sqrt . (+) :. (^2)
kqr
  • 14,791
  • 3
  • 41
  • 72

1 Answers1

24

This function is called on in the Data.Function module.

It's often used infix, such as sqrt . (+) `on` (^2).

Roman Cheplyaka
  • 37,738
  • 7
  • 72
  • 121
  • 2
    I can't believe I didn't think of this! Thanks a bunch. – kqr Sep 28 '13 at 08:14
  • A common example of use is `sortBy (compare \`on\` abs)` – J. Abrahamson Oct 12 '13 at 20:54
  • I'll note for future Google people however that `comparing abs` is more idiomatic than ``compare `on` abs``. This works because `comparing = on compare` is defined somewhere in the standard libraries. – kqr Dec 23 '14 at 10:02