1 title:: Partial Application
2 summary:: Create Functions via Partial Application
4 related:: Reference/Functions
6 Partial application is a way to create a function by passing only some arguments to a method. The code::_:: character stands in for missing arguments and becomes an argument to the created function.
7 It only applies to a single method, list, or dictionary call, not to a more complex nested expression.
13 f is now a function of one argument.
15 f.value(7); // returns 9
17 it is equivalent to having written:
21 (except that there is no name 'x' declared)
26 g is a function of two arguments.
31 Here are some example usages of this in a collect message. Below each is written the equivalent function.
33 (1..8).collect(_.isPrime);
34 (1..8).collect {|x| x.isPrime };
36 (1..8).collect(_.hash);
37 (1..8).collect {|x| x.hash };
39 (1..8).collect([\a, \b, _]);
40 (1..8).collect {|x| [\a, \b, x] };
42 (1..8).collect((a:_));
43 (1..8).collect {|x| (a:x) };
45 (1..8).collect(Polar(_, pi));
46 (1..8).collect {|x| Polar(x, pi) };
48 (1..8).collect((1.._));
49 (1..8).collect {|x| (1..x) };
53 f = (a:_, b:_); // f is a two argument function
54 g = f.(_, 5); // g is a partial application of f
55 g.(7); // get the answer
57 // equivalent to this:
58 f = {|x, y| (a:x, b:y) }
63 An example of what you can't do:
65 (1..8).collect( Point(100 * _, 50) ); // nested expression won't work.
66 // only the * gets partially applied, not the surrounding expression.
68 (1..8).collect {|x| Point(100 * x, 50) }; // need to use a function for this.