14

Say I have two functions:

f(x) = x^2
g(x) = x + 2

Their composition is the function

h(x) = f(g(x))

Is there an operator for function composition in Julia? For example, if * was an operator for function composition (which it isn't), we could write:

h = f * g

P.S. I know I can define it if I want to,

*(f::Function, g::Function) = x -> f(g(x))

Just asking if there is an operator form already in Julia.

a06e
  • 18,594
  • 33
  • 93
  • 169

1 Answers1

16

It is currently an open issue to create such operator, but as now you can keep to the syntax:

julia> h(x) = f(g(x))

or a bit more clearer (for more complex functions):

julia> h(x) = x |> g |> f

It seems as for now you would need to keep the x for making it a composite function.

Another option, is to create your own operator (as you suggest):

julia> ∘(f::Function, g::Function) = x->f(g(x))
julia> h = f ∘ g

This works perfectly fine, however, it introduces a lambda function, and I cannot think a way of performing such operation without lambdas.

NOTE: ∘ operator can be written as \circ as @DanGetz suggested.


EDIT: seems fast closures are coming in future releases and will probably be easy to implement an efficient version of the composite operator.

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67