Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia - Pass keyword arguments to another function?

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

like image 488
Jacob Amos Avatar asked Mar 29 '16 00:03

Jacob Amos


People also ask

Is Julia pass by value?

In Julia, values are passed and assigned by reference.

What is :: In Julia?

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 .

What makes Julia unique?

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.

What is the type of a function in Julia?

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.


1 Answers

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...)
like image 77
Jacob Amos Avatar answered Nov 15 '22 09:11

Jacob Amos