racket Higher Order Functions Compose


Example

Lets you compose several functions f₀ f₁ … fₙ. It returns a function that will successively apply fₙ to its arguments, then fₙ₋₁ to the result of fₙ and so on. Function are applied from right to left, like for mathematical function composition: (f ∘ g ∘ h)(x) = f(g(h(x))).

> ((compose sqrt +) 16 9)
5
> ((compose - sqrt) 16)
-4

The arity of each function should include the the number of returned values of the function immediately to its right. The rightmost function determines the arity of the whole composition. The compose1 function imposes that the functions return 1 value and expect 1 argument. However, compose1 does not restrict the input arity of the last function, nor the output arity of the first function.

[n input]--> first-function -->[1 output]--> ... last function -->[m output].

((compose + values) 1 2 3 4)
10
> ((compose1 + values) 1 2 3 4)
XX result arity mismatch;
 expected number of values not received
  expected: 1
  received: 4
  values...: