Hi, I was wondering about a possible syntax extension “automated argument composition” and if something like this already exists in Julia’s dispatch? The closest I could find is function composition and negation but it’s not quite the same:
I feel there is maybe some headroom in the function dispatch syntax to perhaps support a useful automated argument conversion:
MWE
These are not default arguments, but auto-composition analogous to
f(x::Int=g(x::Symbol), args...)
producing both the “direct” f(::Int, args...)
and “derived” forms f(::Symbol, args...)
from dispatch, but only the argument x::Int
exists in the local scope of f
.
Proposed Usage Example II
Very similar functions but with a “direct” and “derived” argument list, where the convenience
conversion occurs via a (small) helper function.
# as example a simple bridge table...
bridgetable = Dict{Symbol, Int}(:x1=>13, :p56=>402)
helper = (s::Symbol)->bridgetable[s]::Int
# enhanced logical function (with auto-argument-composition)
funtion doSomething!(container::T, id::Int=helper(sym::Symbol), data::AbstractVector; kargs...) where T
container[id] # do stuff...
end
# The user can now simply call any one of at least two auto-composed functions
doSomething!(mycontainer, :x1, rand(5)) # should work just fine but was auto-generated
doSomething!(mycontainer, 13, rand(5)) # equivalent call but is the "direct" format
Current Usage Requires
# the logical function
function doSomething!(container::T, id::Int, data; kargs...) where T
container[id] # do stuff...
end
# the derived function API which user currently has to write themselves.
doSomething!(container::T, sym::Symbol, data; kwargs...) where T = doSomething!(container, helper(sym), data, kwargs...)
Error Handling
Errors in the following case would produce the output
# error on:
doSomething!(mycontainer, rand(5))
## Undef method error since doSomething!(::T, !!!, ::Vector) does not exist.
# either `id::Int` or `sym::Symbol` are not defined
This seems like quite a predictable dispatch case…
Another Example III
This is closer to my own use-case
using IncrementalInference
# this is essentially a LightGraphs.jl object
fg = generateCanonicalFG_lineStep(5)
doSomething!(vari::DFGVariable, data) = # do something with vari
doSomething!(fg::AbstractDFG, sym::Symbol, data) = doSomething!(getVariable(fg, sym), data)
So I find a lot of repetition which cannot really be avoided unless some kind of automated argument composition could occur during dispatch. Would be great if one could instead just write:
doSomething!(vari::DFGVariable=getVariable(fg::AbstractDFG, sym::Symbol), data) = # do somethng with vari
Again, only vari
is visible inside the auto-composed function, so it does not change the body of a function in any way.