Optional arguments+splatting

Julia’s creators say they are greedy - so am I. I want to create a function g that accepts a list of arguments (I am trying with a named tuple), and passes it on to a function f. I have 3 requirements

  • The user of g must provide “named arguments” as in “a=3”, for readability of the code calling g
  • Arguments must be optional, with fallback on a default value
  • and here comes the crunch: g must not be concerned with the details of this argument list.

Why would I ever want to do that? Well, in the real world, g does a bit of work behind the scenes.

I try

struct T
    a
    b
end
f(;a=0,b=0) = T(a,b)
g(foo,s...) = foo(s...)
r=g(f,(a=2))

but splatting was clearly not intended for named tuples. Any ideas that do not involve metaprogramming? :grinning:

I am knocking off for the day, but I am wondering if g could become a macro… metaprogramming-light.

Maybe you meant

foo(; s...) 

?

I can’t test this right now, BTW.

3 Likes

Building up DFN’s answer, I think you want the following:

struct T
  a
  b
end
f(;a=0, b=0) = T(a ,b)
g(foo, s) = foo(;s...)
r = g(f,(a=2,))

Note that (a=2,) requires a comma because there is only 1 element. Otherwise, the parentheses are omitted. Also, I removed the splatting on s in g

2 Likes

Thank you, that’s it!

1 Like

Even sweeter:

struct T
  a
  b
end
f(;a=0, b=0) = T(a ,b)
g(foo; s...) = foo(;s...)
r = g(f,a=2)  # no tuple syntax !

:grin:

2 Likes