On 2022-11-18 10:21, Bruce Axtens wrote:
> There's a programming exercise on Exercism called two-fer.
> It takes an optional parameter. If the parameter is absent
> it returns "One for you, one for me." If the parameter is present
> it is interpolated into the string in place of the "you".
The standard means for strings interpolation are the words "replaces"
and "substitute". Although they are not enough convenient and so rarely
used. NB: "replaces" may use data space.
> As I understand it, and i'm no Forth programmer, optional items aren't a thing
> in Forth. Rather, you either program for something or program for nothing.
> Thus, a two-fer word would expect a null-string or maybe even a null.
>
> Am I understanding this right?
Yes.
Positional parameters, except parameters at the tail of a parameters
list, cannot be missed in any programming language — you have to pass
something in every position.
Named parameters can be missed. But for a missed parameter some default
value is available anyway (e.g. "undefined" in JavaScript).
In Forth, a list of parameters is not delimited, so no parameters can be
missed.
Though, you can pass a counter (or a map of parameters) as the top
parameter, and then the number of parameters can vary.
For example:
: two-fer ( sd1 1 | 0 -- sd2 )
0= if s" you" then s" another-side" replaces
s" One for %another-side%, one for me." pad 84 substitute
0< if 2drop 0. then
;
0 two-fer cr type
s" World" 1 two-fer cr type
Another solution is to pass some default value, which means that the
actual value is missed for the parameter. E.g. the pair ( 0 0 ) for a
missed string.
: two-fer ( sd1 | 0 0 -- sd2 )
over 0= if 2drop s" you" then s" another-side" replaces
s" One for %another-side%, one for me." pad 84 substitute
0< if 2drop 0. then
;
0 0 two-fer cr type
s" World" two-fer cr type
--
Ruvim