添加两个函数的新功能

New function by adding two functions

是否可以通过在 Julia 中添加另外两个函数来创建一个新函数?我想做这样的事情:

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

Julia 中的每个函数[1] 都是一个多方法,可以事后扩展。如果我们尝试做 quadratic + cubic,我们会收到一条消息

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

这并不是说 永远不会 成为实现这一目标的方法;据说 还没有人愿意这样做。让我们编写一个适用于函数的版本。

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

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

现在我们可以写了

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

[1] 从技术上讲,有一些低级的自举函数非常神奇且无法扩展,但 + 不是其中之一。

有一个不太神奇的解决方案是f(x) = quadratic(x) + cubic(x)