Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: using splat to pass along arguments

Tags:

splat

julia

I am trying to write a function that calls several functions that accept named parameters. I'd like the A function to be able to named parameters splatted together in args and pass along the matching arguments to the functions 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 of getting this to work? Adding "args..." into the argument list of B fixes the error, but I'm not sure if it's a good idea (e.g. is there any performance hit).

like image 611
Rob Donnelly Avatar asked Mar 10 '15 05:03

Rob Donnelly


1 Answers

Your solution 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

Theres no special meaning to _, use whatever feels best to you.

As to performance, I doubt it'd noticeable. Are you calling B many times in a hot loop and using the values of the keyword arguments in calculations? They aren't typed very well, so that could be only thing (although its not really relevant to the specific question).

like image 50
IainDunning Avatar answered Sep 19 '22 08:09

IainDunning