Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an operator for function composition in Julia?

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.

like image 414
becko Avatar asked Mar 30 '16 15:03

becko


People also ask

What is function composition operator?

In mathematics, function composition is an operation ∘ that takes two functions f and g, and produces a function h = g ∘ f such that h(x) = g(f(x)). In this operation, the function g is applied to the result of applying the function f to x.

What is the operator in Julia?

Operators in Julia are the mathematical symbols that are used to perform operations on variables and values. These symbols are used to carry out arithmetic and logical computations. Variables on which the operators perform operations are termed as Operands.

How do I write ∘ in Julia?

Getting started with ∘ The ∘ symbol can be entered in the Julia REPL (and most editors, appropriately configured) by typing \circ<tab>. Function composition also works in prefix form: ∘(f, g) is the same as f ∘ g.


1 Answers

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.

like image 64
Imanol Luengo Avatar answered Sep 22 '22 06:09

Imanol Luengo