tuples, apply/splicing, and keyword arguments

98 views
Skip to first unread message

Tamas Papp

unread,
May 2, 2015, 8:34:25 AM5/2/15
to Julia Dev
Hi,

I could not figure out the answers to questions below from the manual
(using nightly snapshot):

1. How to use apply or ... (splicing) with keyword arguments? Eg suppose
I have

foo(a;b=1,c=2) = (a,b,c)

and want to use apply in a manner equivalent to

foo(4;b=5,c=6)

then is the relevant syntax

foo((4)...;Dict(:b=>5,:c=>6)...)

? I found this by experimentation, and I am wondering if it is here to
stay.

2. Can I use apply for the same purpose? How?

3. The manual says that "Tuples are an abstraction of the arguments of a
function", how do keyword arguments fit in? Or are they not covered by
tuples?

Best,

Tamas

Yichao Yu

unread,
May 2, 2015, 9:36:07 AM5/2/15
to Julia Dev
Not an expert on julia internals but here's the code I used to figure
this out (kind of ....).

julia> f(args...; kwargs...) = (args, kwargs)
f (generic function with 1 method)

julia> f(1, 2; a=3, b=4)
((1,2),Any[(:a,3),(:b,4)])
# so kwargs is packed into an Any array of (<name>::Symbol, <value>)

julia> f((1, 2)...; [(:a, 3), (:b, 4)]...)
((1,2),Any[(:a,3),(:b,4)])
# and can be unpacked that way

#things that can be unpacked to the same value should work too. i.e.
julia> (Dict(:a=>3, :b=>4)...)
((:a,3),(:b,4))

julia> ([(:a, 3), (:b, 4)]...)
((:a,3),(:b,4))

> Best,
>
> Tamas

Tamas Papp

unread,
May 2, 2015, 9:52:45 AM5/2/15
to juli...@googlegroups.com
Thanks. My approach is also experimental :D

I am now wondering if apply is redundant: since Julia is a Lisp-1, you
can do everything that apply can do with function calls, eg

julia> foo(a,b;kwargs...)=(a,b,kwargs)
foo (generic function with 2 methods)

julia> bar(b,a;kwargs...)=(a,b,kwargs)
bar (generic function with 1 method)

julia> (x ? foo : bar)(1,2;[(:c,3),(:d,4)]...)
(1,2,Any[(:c,3),(:d,4)])

but on the other hand apply cannot deal with keyword arguments.

Best,

Tamas

Yichao Yu

unread,
May 2, 2015, 10:42:11 AM5/2/15
to Julia Dev
And so apply is deprecated in 0.4-dev.

Also from a user perspective combined with what I saw from
code_lowered and code_typed, (also at least on 0.4) _apply is still
internally used sometimes to call functions with unknown number of
arguments.

julia> @noinline f(args...) = args
f (generic function with 1 method)

julia> g(args) = f(1, args...)
g (generic function with 1 method)

julia> @code_typed g([1, 2])
1-element Array{Any,1}:
:($(Expr(:lambda, Any[:args],
Any[Any[],Any[Any[:args,Array{Int64,1},0]],Any[],An
y[]], :(begin # none, line 1:
return (top(_apply))(call,f,(top(tuple))(1)::Tuple{Int64},args::Array{Int6
4,1})::Tuple
end::Tuple))))

julia> apply(f, [1, 2])
WARNING: apply(f, x) is deprecated, use `f(x...)` instead
in apply at ./deprecated.jl:93
(1,2)
Reply all
Reply to author
Forward
0 new messages