Pedro Rafael
Pedro Rafael

Reputation: 522

Keyword Arguments - Functions

I am a beginner in Julia,

how can I create functions with keywords for arguments without having to initialize these arguments in function?

A very simple example:

function f(;a = 1, b = 2)
 a+b
end

I would like to do:

function f(;a, b)
 a+b
end

Best regards.

Upvotes: 1

Views: 431

Answers (3)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22225

Another workaround is to create a function with variadic keyword arguments and leave any requirements over the expected keyword inputs as assertions inside the code. E.g.

function f( ; kwargs... )
  V = Dict( kwargs )
  try; assert( haskey( V, :a ) ); assert( haskey( V, :b ) )
  catch e; throw( AssertionError("KWargs need to be a and b") )
  end
  V[:a] + V[:b]
end

f(a=1, b=2)   #> 3

f(a=1, c=2)   #> ERROR: AssertionError: KWargs need to be a and b

Or even as simple as:

function f( ; kwargs... )
  V = Dict( kwargs )
  a = V[:a]
  b = V[:b]
  a + b
end

f(a=1, c=2)   #> ERROR: KeyError: key :b not found

Disclaimer: I'm not recommending this, I'm just saying it's another workaround to consider depending on what functionality you have in mind.

Upvotes: 3

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

This is comming in Julia 0.7 line:

Keyword arguments can be required: if a default value is omitted, then an exception is thrown if the caller does not assign the keyword a value (#25830).

So:

function f(;a, b)
    a+b
end

Will become syntax sugar for:

function f(;a = throw(UndefKeywordError(:a)), b = throw(UndefKeywordError(:b)))
    a+b
end

Upvotes: 4

mbauman
mbauman

Reputation: 31342

This is a new feature in version 0.7 — you can actually write it just as you'd like.

Julia's syntax on versions 0.6 and prior require you to give them a default value, but since that default value is evaluated at call time, you can actually use an error function to require them:

julia> function f(;a=error("a not provided"), b=error("b not provided"))
        a+b
       end
f (generic function with 1 method)

julia> f()
ERROR: a not provided
Stacktrace:
 [1] f() at ./REPL[1]:2

julia> f(a=2)
ERROR: b not provided
Stacktrace:
 [1] (::#kw##f)(::Array{Any,1}, ::#f) at ./<missing>:0

julia> f(a=2, b=3)
5

Upvotes: 6

Related Questions