Alex Craft
Alex Craft

Reputation: 15336

Reference all the arguments in Julia

Is it possible to capture all the arguments and pass it to another function?

To make code like that shorter:

function send_binary(;
  binary_hash::String,
  binary::String
)::Any
  post_json(
    "http://localhost:$(port)/v1/binaries",
    json((binary_hash=binary_hash, binary=binary))
  )
end

(theoretical) Shorter version:

function send_binary(;
  binary_hash::String,
  binary::String
)::Any
  post_json("http://localhost:$(port)/v1/binaries", json(arguments))
end

Upvotes: 3

Views: 96

Answers (2)

Steven Siew
Steven Siew

Reputation: 873

You can do this

using Plots

function myplot(func;moreargs...)
    plot([k for k = 0:0.01:2*pi],[func(k) for k = 0.0:0.01:2*pi];moreargs...)
end

myplot(sin,legend=false)
myplot(x->(sin(x)+cos(x)),legend=false)

Upvotes: 1

David Sainez
David Sainez

Reputation: 6956

The splat operator captures arguments in function definitions and interpolates arguments in function calls:

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

julia> foo(; kwargs...) = bar(; kwargs...)
foo (generic function with 1 method)

julia> foo(; a=1, b=2)
(1, 2)

julia> foo()
(0, 0)

julia> foo(; b=1)
(0, 1)

Your example can be written as:

function send_binary(; kwargs...)
  return post_json("http://localhost:$(port)/v1/binaries", json(; kwargs....))
end

Upvotes: 6

Related Questions