Curried Subroutines

Currying[14] 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:

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

[14] The term “currying” is drawn from functional languages and is named in honor of logician Haskell Curry.

Get Perl 6 and Parrot Essentials, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.