5.8 Curried Subroutines

     

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 



Perl 6 and Parrot Essentials
Perl 6 and Parrot Essentials, Second Edition
ISBN: 059600737X
EAN: 2147483647
Year: 2003
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net