3

I'm trying to learn function composition in Haskell. I have following exercise.
I have function:h x y = f (g x y)and i need to find function composition equal to it:

a) f . g  
b) (f.).g  
c) (.)f(.g)  
d) f(.g)

I know that (.)f g = f.g = f(g x) but i don't understand this complicated function composition

Tomasz
  • 191
  • 2
  • 12

2 Answers2

4

The correct answer is (b): (f.).g

Let us analyze this function. The (f.) part is short for ((.) f), so we already solved that one, and thus the function - without syntactical sugar - is:

(.) ((.) f) g

Now we can rewrite the first (.) function to a lambda-expression:

\x -> ((.) f) (g x)

And now when we evaluate the second function on the left (((.) f)) further, we obtain:

\x -> (.) f (g x)

or:

\x -> f . g x

So if we convert the (.) function in a lambda expression, we obtain:

\x -> (\y -> f ((g x) y))

Now we can make this expression more elegantly. (g x) y can be rewritten to g x y:

\x -> (\y -> f (g x y))

and we can rewrite nested lambda expressions into a single lambda expression:

\x y -> f (g x y)

Which is what we wanted.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
3

You can also use (.) (.) (.) - despite it being somewhat challenging to understand, the evaluation results in an elegant form identical to the one you're looking for

comp2 = (.) (.) (.)
comp2 f g x y == f (g x y)

Evaluation of (.) (.) (.)

-- comp
(.) = \f -> \g -> x -> f (g x)

-- evaluate
(.) (.) (.)
(\f -> \g -> \x -> f (g x)) (.) (.)
(\g -> \x -> (.) (g x)) (.)
\x -> (.) ((.) x)
\x -> (\f -> \g -> \x' -> f (g x')) ((.) x)
\x -> \g -> \x' -> ((.) x) (g x')
\x -> \g -> \x' -> ((\f -> \g' x'' -> f (g' x'')) x) (g x')
\x -> \g -> \x' -> (\g' -> \x'' -> x (g' x'')) (g x')
\x -> \g -> \x' -> \x'' -> x ((g x') x'')
\x -> \g -> \x' -> \x'' -> x (g x' x'')

-- alpha rename
\f -> \g -> \x -> \y -> f (g x y)

-- collapse lambdas 
\f g x y -> f (g x y)

Understanding a pattern of (.) compositions

-- comp2
comp2 = (.) (.) (.)
comp2 f g x y == f (g x y)

-- comp3
comp3 = (.) (.) comp2
comp3 f g x y z == f (g x y z)

-- comp4
comp4 = (.) (.) comp3
comp4 f g w x y z == f (g w x y z)
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • 3
    I downvoted, for three reasons: 1. The level of knowledge displayed in the question doesn't support the assumption that the behavior of this kind of double-composition would be immediately apparent to the question asker, so some explanatory sentences at the beginning are needed. 2. This doesn't actually "tie the knot" back to the original question, so some explanatory sentences at the end are needed to show how we can start with double-composition of this form and end with one of the four possible choices. 3. I agree that this is a stupid name for it. So don't propagate that name! – Daniel Wagner Jun 21 '17 at 19:06
  • @DanielWagner thanks for the thorough comment. I've adjusted my answer some in hopes that it's more informative. – Mulan Jun 21 '17 at 19:32