-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
allow default arguments at any place in a function #22460
base: master
Are you sure you want to change the base?
Conversation
Why the brackets? |
Currently, EDIT: it is possible with the macro to mix bracketed defaults (doubles the number of generated methods) and regular defaults (generates one more method). |
-1 on this syntax, square brackets are for array literals, they shouldn't have a different meaning in function definitions
Not if we remove this non-syntax from the docstrings. |
Couldn't we allow |
It would not be the first time that Julia has overloaded meaning for syntax, but I'm not particularly attached to this bracket syntax here. Another possibility I see is
I think it would be difficult without changing the current rules to the ones proposed here (i.e. 2^n generated methods vs. n+1), and I think it is out of question to change the current rules. For example how many methods would be generated for |
This is more a feature idea, with a proof of concept via a macro
@defaults
, rather than a PR.In Julia, it's not possible to get a default argument before a non-default, so to simulate that functionality, one usually has duplicate the methods signatures by hand. But in the docstrings, we specify a default arg at any position with the use of brackets, e.g.:
I propose to allow that syntax in real code: Julia will automatically duplicate the signature (and forward the default argument when it's not supplied, similarly to what happens with regular default args) for each argument with a bracket (this means
2^n
methods ifn
args have a bracket). It's up to the user to handle ambiguities (e.g. withf([a=0], [b=0])=...
, the callf(0)
is ambiguous).This would not cover all our docstring uses (where sometimes the default is not shown), but could be a good step forward.
For the cons, I see that 1) it makes the language a bit more complicated (but anyway the user has to face this syntax in docstrings), and 2) it prevents using this syntax in the future for destructuring arguments (a la Haskell, e.g. defining
f([a, b], c=>d) = a+c
and being able to callf([1, 2], 3=>4)
, wherea
will take value1
, etc.), but I didn't notice such a proposition yet.This PR shows how the
rand
methods could be updated with this syntax: basically the number of methods is halved (or even decreased from 8 to 2 forrandn/randexp
).If in base, I believe it would be nicer without a macro, but a package with this macro is likely to be sufficient (the impact on Base itself doesn't seem so big).
(For reference, this issue has some related comments).