55 lines
1.4 KiB
Markdown
55 lines
1.4 KiB
Markdown
|
# Partial functions
|
||
|
|
||
|
If a function is supplied with more arguments than it expects, it will throw
|
||
|
an exception. If it is supplied with too few arguments, however, it will return
|
||
|
a *partially-applied function* (or partial function for short). This value may
|
||
|
then be called with the remaining arguments and the expected result will be
|
||
|
returned.
|
||
|
|
||
|
```talc
|
||
|
>> add_nums = \x,y,z -> x + y + z
|
||
|
<anon function(3) @58e147c31910>
|
||
|
>> add_nums(5, 6, 8)
|
||
|
19
|
||
|
>> add5 = add_nums(5)
|
||
|
<anon native function(2) @58e147c329e0>
|
||
|
>> add5_and6 = add5(6)
|
||
|
<anon native function(1) @58e147c33360>
|
||
|
>> add5_and6(8)
|
||
|
19
|
||
|
```
|
||
|
|
||
|
Note that each time the function is given an argument the number the result
|
||
|
expects decreases by one.
|
||
|
|
||
|
## Pipes
|
||
|
|
||
|
An alternate way of calling a function with one argument is using the pipe
|
||
|
operator (`|`). The order is reversed to a normal function call - the argument
|
||
|
is written before the pipe.
|
||
|
|
||
|
```talc
|
||
|
>> sin(2)
|
||
|
0.9092974268256817
|
||
|
>> 2 | sin
|
||
|
0.9092974268256817
|
||
|
```
|
||
|
|
||
|
Partial application combines very nicely with pipes: functions may first be
|
||
|
called with all but one of their arguments, and the resulting partially-applied
|
||
|
function may be called using a pipe.
|
||
|
|
||
|
```talc
|
||
|
>> gcd(70, 15)
|
||
|
5
|
||
|
>> 15 | gcd(70)
|
||
|
5
|
||
|
```
|
||
|
|
||
|
Note that the argument to the left of the pipe becomes the *final* argument to
|
||
|
the function. This is the opposite of langauges like Elixir, in which it
|
||
|
becomes the initial argument.
|
||
|
|
||
|
Pipelines will be featured heavily in the chapter on
|
||
|
[ranges and iterators](./iterators.md).
|