Is there an operator for function composition in Julia?
Asked Answered
O

2

15

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.

Ortrude answered 30/3, 2016 at 15:58 Comment(3)
Perhaps using the operator (enter using \circ TAB at REPL) will serve for a better math-y look.Forebode
@DanGetz Agree, but that is also undefined by default.Ortrude
The route for getting to default would likely be: Define in your code -> In a package -> In a popular package -> In Base.Forebode
S
2

Coming here later. is available by default

Spectre answered 3/10, 2023 at 19:58 Comment(1)
Yes, since github.com/JuliaLang/julia/pull/17155 Julia now has the operator for function composition.Ortrude
S
17

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.

Scoter answered 30/3, 2016 at 21:32 Comment(3)
fast closures are now in Julia 0.5. Any updates on a composition operator?Ortrude
This is now in Julia 0.6 (as ∘ )Herbherbaceous
@Imanol As yours is the accepted answer, perhaps you would consider updating it with a note that \circ is now the composition operator? Thanks.Neutretto
S
2

Coming here later. is available by default

Spectre answered 3/10, 2023 at 19:58 Comment(1)
Yes, since github.com/JuliaLang/julia/pull/17155 Julia now has the operator for function composition.Ortrude

© 2022 - 2024 — McMap. All rights reserved.