Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A common pattern involving composition of functions (\a b -> f (g a) (g b))

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)
like image 964
kqr Avatar asked Sep 28 '13 07:09

kqr


1 Answers

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

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

like image 177
Roman Cheplyaka Avatar answered Oct 02 '22 12:10

Roman Cheplyaka