Suppose I have a series of functions with keyword arguments of different names
foo(x, y; a=1, b=2) = (a + b) / (x + y)
bar(x, y; c=3, d=4) = (x - y) * (c - d)
And suppose I have third function that takes a function as an argument. I want to be able to pass any keyword argument(s) through to one of the first two functions when calling this third function.
master(x, y; fun::Function=foo, args...) = fun(x, y, args...)
My problem arises when trying to call the master
function using keyword arguments.
julia> master(pi, e, fun=bar)
-0.423310825130748
julia> master(pi, e, fun=bar, c=4)
ERROR: MethodError: `bar` has no method matching bar(::Irrational{:π}, ::Irrational{:e}, ::Tuple{Symbol,Int64})
Closest candidates are:
bar(::Any, ::Any)
Is there a way to pass through the keyword arguments without having to iteratively check the argument names?
Please let me know if the question is unclear and I'd be happy to clarify. I've looked for other questions, but the solutions I've seen generally show how to grab the name-value pairs, not how to pass them through to other functions with keyword arguments
In Julia, values are passed and assigned by reference.
A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .
Julia has a sophisticated type system and allows multiple dispatch on argument types. None of the examples given here provide any type annotations on their arguments, meaning that they are applicable to all types of arguments.
Method Tables Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable ) are associated with TypeName s.
To highlight the answer spencerlyon2 gave in his comment, my problem was using a comma (,
) instead of a semicolon (;
) to separate the keyword arguments when calling fun
.
WRONG:
master(x, y; fun::Function=foo, args...) = fun(x, y, args...)
RIGHT:
master(x, y; fun::Function=foo, args...) = fun(x, y; args...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With