MetaColon
MetaColon

Reputation: 2871

Julia identify method by number of keyword arguments

I have two methods with the same name and same amount of "normal" arguments. However, they differ in the number of keyword arguments (which are all non-optional).

I think the following minimal example illustrates my point well:

julia> f(a; b) = a+b
f (generic function with 1 method)

julia> f(a; b, c)= a+b+c
f (generic function with 1 method)

julia> f(1; b=1)
ERROR: UndefKeywordError: keyword argument c not assigned
Stacktrace:
 [1] top-level scope
   @ REPL[72]:1

julia> f(1; b=1, c=2)
4

The second line of output ("f (generic function with 1 method)") already shows that Julia doesn't understand what I want - it should be 2 methods (which it would be e.g. if I wrote f(a, b; c) = a+b+c).

I already found this in the Julia discourse forum, which seems to explain why this doesn't work for multiple dispatch. However, in my case not the types but the counts differ, so I hope that there is a (neat) solution.


Regarding why I want this: I have a function that makes some calculations (to be precise it calculates Stark curves) for different molecules. This function needs to act differently for different molecule types (to be precise different symmetries) and also takes different arguments (different quantum numbers).

So that's why I need multiple dispatch - but why keyword arguments, you might ask. That is because I create the quantum numbers using distributions and passing them as NamedTuple in connection with ....

I'd like to not change this behaviour, but maybe you were curious to why I would need something like this.

Upvotes: 1

Views: 230

Answers (1)

BatWannaBe
BatWannaBe

Reputation: 4510

In your example, you can reuse the keyword arguments as positional arguments to make f(1; b=1) work, but it won't behave like true keyword dispatch. For one, f(1; c=2) would call _f(a,b).

function f(a; b=missing, c=missing)
    _f(a, skipmissing((b, c))...)
end

_f(a,b,c) = a+b+c
_f(a,b) = a+b

Not sure if this is applicable to the actual use case you described, though, things can be harder to reorder than b and c, and as a comment noted, a NamedTuple (which is ordered) is already dispatchable.

Upvotes: 1

Related Questions