New function by adding two functions

Viewed 76

Is it possible to create a new function from the addition of two other functions in Julia? I want to do something like this:

function quadratic(x)
  return x^2
end

function cubic(x)
  return x^3
end

f::Function = quadratic + cubic
# such that f(x) returns x^2 + x^3

2 Answers

There is the less magic solution which is f(x) = quadratic(x) + cubic(x)

Every function[1] in Julia is a multimethod and can be extended after-the-fact. If we try to do quadratic + cubic, we get a message

ERROR: MethodError: no method matching +(::typeof(quadratic), ::typeof(cubic))

This isn't saying there will never be a way to make that work; it's saying nobody has bothered to do it yet. Let's write a version that works on functions.

# Extend the existing +, don't shadow it
import Base.+

+(f::Function, g::Function) =
    (args...; kwargs...) -> f(args...; kwargs...) + g(args...; kwargs...)

Now we can write

fn = quadratic + cubic
println(fn(10)) # 1100

[1] Technically, there are a handful of low-level bootstrapping functions that are deep magic and can't be extended, but + is not one of those.

Related