Julia: using splat to loop through arguments

I am trying to write a function that calls several functions that take named parameters. I would like function A to be able to have named parameters combined together in args, and pass in the corresponding arguments to the functions that it calls.

function A(x, y; args...)
  B(x; args...)
  C(y; args...)
end
function B(x; a=0)
  println(x,a)
end
function C(y; a=0, b=0)
  println(y,a,b)
end

funcA(1, 2) # Works
funcA(1, 2, a=1) # Works
funcA(1, 2, a=1, b=1) # Error: unrecognized keyword argument "b"

What is the preferred way to make this work? Adding "args ..." to argument list B fixes the error, but I'm not sure if this is a good idea (for example, is there any kind of performance hit).

+4
source share
1 answer

Your decision is the preferred way.

function A(x, y; args...)
  B(x; args...)
  C(y; args...)
end
function B(x; a=0, _...)  # catch rest
  println(x,a)
end
function C(y; a=0, b=0)
  println(y,a,b)
end

A(1, 2) # Works
A(1, 2, a=1) # Works
A(1, 2, a=1, b=1) # Works

_, , .

, , . B ? , ( ).

+3

All Articles