To make a function with default argument, I tried this:
f: function [a b] [either unset? :b [a + 1] [a + b]]
f 5
f 3 5
then I receive this message *** Script Error: f is missing its b argument.
So, what shall I do?
On
You can use a refinement. See: http://helpin.red/Functions.html
For example:
>> increase: function [a /add b] [either none? b [a + 1] [a + b]]
== func [a /add b][either none? b [a + 1] [a + b]]
>> increase 3
== 4
>> increase/add 3 5
== 8
There's a trick to implement variable-arity functions that some of the built-ins use, most notably
help:Specify your argument as quoted and belonging to
any-type!typeset. Or, alternatively, list the allowed types and includeunset!in it.This, however, comes at a certain price:
any-type!accepts any argument;'in front of the argument also enforces specific semantics, which makes such variadic functions even more cumbersome.block!argument, which might even be dialected.Such an approach is justified only for user-facing polymorphic functions, intended to be used from command-line prompt (such as
help) or any other kind of interface that provides clear-cut boundaries for typed expressions (e.g. end of the line, special terminating symbol), and even then the number of optional arguments is kept at minimum.