YS Multi Functions
Many languages let you define functions with multiple signatures.
That is, you can have multiple functions with the same name but different arguments.
YS supports multi-arity functions. It dispatches on the number of arguments.
Let's see how it works.
Extending defn
🔗
Let's concoct a multi-arity function called weird
that does the following
based on the number of numbers it is given:
- 1 number: returns the square of the number
- 2 numbers: returns the sum of the numbers
- 3 numbers: returns the product of the numbers
# weird.ys
!YS-v0
defn weird:
(x): x ** 2
(x y): x + y
(x y z): x * y * z
say: ~weird(3)
say: ~weird(3 5)
say: ~weird(3 5 7)
say: ~weird(3 5 7 9)
And let's run it:
$ ys weird.ys
9
8
105
Error: Cannot call weird with 4 arguments
It works as expected.
When we defined the function we didn't use any parens after the function name. Then we specified a key/value pair for each different function signature and body.
What about any number of arguments?🔗
Now let's modify the weird
function to take any number of arguments.
If it gets 4 or more, let's turn them into a string that is the list of the
numbers separated by commas.
# weird.ys
!YS-v0
defn weird:
(x): x ** 2
(x y): x + y
(x y z): x * y * z
(*more): more.join(', ')
nums =: 1 .. 10
say: weird(nums*)
And:
$ ys weird.ys
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Cool.
An argument with a *
in front of it means "any number of arguments" and
collects them into a list.
We can then "splat" or "unpack" the list into multiple arguments by placing a "*" after the variable name when used in a function call.
A common use case🔗
Let's create a function called add
that takes any number of arguments and
returns the sum of the arguments.
# add.ys
!YS-v0
defn add:
(): 0
(x): x
(x y): x + y
(x y *xs):
reduce add: (x + y) xs
add: 1 2 3 4 5
And:
$ ys add.ys
15
Here when we have more than 2 arguments, we use recursion to add the numbers. You'lll have to wait for another day to learn how reduce works (but it's really simple).
Note
YS has a standard library function called add
and that's exactly how it is
implemented!
See you next time!