Composition of a function and a value

Viewed 102

I'd like to avoid brackets in applying a composition of functions to a value. I come up with the idea to compose a function and a value:

julia> ∘(f::Function, x::Number)=f(x)
∘ (generic function with 2 methods)

julia> sqrt ∘ abs ∘ -2
1.4142135623730951

julia> sqrt ∘ abs ∘ (1-3)
1.4142135623730951

My question is how to declare the x argument to accept a "value" which is not a function, so that it does not overwrite the ∘(f::Function, g::Function)

2 Answers

What does compose a function and a value mean? Might it mean scaling with a constant value? e.g. sqrt ∘ abs ∘ x->-2x(this gives you a function, not the result). But it seems what you would like to do is just applying the function to a value, in this case, you could write -2 |> sqrt ∘ abs if you really really hate brackets. I agree with you that overwrite the ∘ is not a good idea, cause it breaks the concept of function composition.

I don't know if it is a good idea but you could probably use this:

∘(f, g) = f(g)                                              # define for all
∘{S<:Function,T<:Function}(f::S, g::T) = (x...)->f(g(x...)) # but not for fnc

edit: I guess you don't want to redefine functionality for any subtype of Function

edit2: needed bigger redefinition

You don't avoid brackets though:

sqrt ∘ abs ∘ (x->2x) ∘ 1 
Related