Using keyword arguments, default arguments, with and without Unitful

Hi, I have a complicated function which has enough arguments that I want to use keyword args, and I want to have some default values, and in the early stages I like to use Unitful to help me catch dimensional errors, but at other times I would like to be able to just use SI throughout and drop all the clutter of the units.

I can do that in the following way:

f_(a,b) = a+b # imagine a bit more complexity here!
f(a,b=1.0) = f_(a,b)
f(a::Quantity,b::Quantity = 1.0u"m") = f_(a,b)

and then f(2.0e-3) and f(2.0u"mm") both do what I would want.

I feel like there should be a way for multiple dispatch to solve this for me, but in my attempts I’ve only figured out new ways to generate a stack overflow.

[EDIT: simplified MWE]

you can use Length to make sure the quantities will be able to add up:

import Unitful: Length
f(a::Length, b::Length = 1.0m) = f_(a,b)

you can get rid of the units with ustrip (don’t forget to give the reference unit)

julia> ustrip(2mm)
julia> ustrip(m, 2mm)
julia> ustrip(Float64, m, 2mm)

After noodling some more and being reminded that Julia’s multiple dispatch doesn’t allow multiple keyword-only methods of the same function, I think I’ll do the following for now:

f(a,b) = a+b # imagine a bit more complexity here!
f(;a=1.0,b=1.0) = f(a,b)
uf(;a::Quantity = 1.0u"m", b::Quantity = 1.0u"m") = f(a,b)

Edit: On the other hand, keyword args don’t play well with dot fusion which tips it towards my initial solution.

Keywors arguments don’t participate in Dispatch at all, that’s why only one set per function works.

1 Like