Does Julia have an operator for composing functions?

Let's say I have two functions:

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

Their composition is a function

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

Does Julia have an operator for composing functions? For example, if * was an operator for composing functions (which is not the case), we could write:

 h = f * g 

PS I know that I can identify him if I want,

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

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

+7
function-composition julia-lang
source share
1 answer

Currently open the problem to create such a statement, but now you can save the syntax:

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

or a little more clearly (for more complex functions):

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

It seems you now need to save x to create its composite function.

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

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

This works fine, however it introduces a lambda function, and I cannot imagine a way to perform such an operation without lambdas.

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


EDIT: It seems that quick closures will appear in future releases and it will probably be easy to implement an efficient version of the compound statement.

+11
source share

All Articles