Variable sized keyword arguments in Julia

172 views Asked by At

I'm writing a convex solver, for concreteness' sake assume it's solving ordinary least squares: find x that minimizes ||b-Ax||^2. So my function call would look like

x = optim(A, b)

I would like to be able to use warm-starts when they are useful, to provide a good initial guess at the solution. So something like

x = optim(A, b; w=some_starting_value)

My problem is that if I want to use a default value, some_starting_value needs to be of length equal to the number of columns in A, which is chosen by the user. In R it's possible to do something like

x = optim(A, b; w=ncols(A))

Does any similar functionality exist in Julia? My current solution is to do something like

x = optim(A, b; w=0)

and then check if w != 0 and set it to be the right size vector inside the optim function. But that seems hacky and (I assume) messes with type stability.

Is there a clean way to specify a keyword argument whose size depends on a required argument?

Edit It looks like something like

function foo{T<:Real}(A::Array{T,2}; w=zeros(T,size(x,2)))
    println("$x")
    println("$y")
end

will do the trick.

1

There are 1 answers

0
evan.oman On BEST ANSWER

It appears that default parameters in Julia can be expressions containing the values of the other parameters:

julia> a(x, y=2*x) = println("$x, $y")
a (generic function with 2 methods)

julia> a(10)
10, 20

Additionally the default parameter expressions can make calls to other functions:

julia> b(x) = sqrt(x)
b (generic function with 1 method)

julia> a(x, y=b(x)) = println("$x, $y")
a (generic function with 2 methods)

julia> a(100)
100, 10.0