Perl 6 and Parrot Essentials, Second Edition

     

5.8 Curried Subroutines

Currying [6] allows you to create a shortcut for calling a subroutine with some preset parameter values. The assuming method takes a list of named arguments and returns a subroutine reference, with each of the named arguments bound to the original subroutine's parameter list. If you have a subroutine multiply that multiplies two numbers , you might create a subref $six_times that sets the value for the $ multiplier parameter, so you can reuse it several times:

[6] The term "currying" is drawn from functional languages and is named in honor of logician Haskell Curry.

sub multiply ($multiplicand, $multiplier) { return $multiplicand * $multiplier; } $six_times = &multiply.assuming(multiplier => 6); $six_times(9); # 54 $six_times(7); # 42 . . .

You can also use binding assignment to alias a curried subroutine to an ordinary subroutine name instead of a scalar variable:

&six_times := &multiply.assuming(multiplier => 6); six_times(7); # 42

Категории