Categories
Posts in this category
- Introduction
- Strings, Arrays, Hashes;
- Types
- Basic Control Structures
- Subroutines and Signatures
- Objects and Classes
- Contexts
- Regexes (also called "rules")
- Junctions
- Comparing and Matching
- Containers and Values
- Where we are now - an update
- Changes to Perl 5 Operators
- Laziness
- Custom Operators
- The MAIN sub
- Twigils
- Enums
- Unicode
- Scoping
- Regexes strike back
- A grammar for (pseudo) XML
- Subset Types
- The State of the implementations
- Quoting and Parsing
- The Reduction Meta Operator
- The Cross Meta Operator
- Exceptions and control exceptions
- Common Perl 6 data processing idioms
- Currying
Wed, 27 May 2009
The Cross Meta Operator
Permanent link
NAME
"Perl 5 to 6" Lesson 25 - The Cross Meta Operator
SYNOPSIS
for <a b> X 1..3 -> $a, $b { print "$a: $b "; } # output: a: 1 a: 2 a: 3 b: 1 b: 2 b: 3 .say for <a b c> X 1, 2; # output: a 1 a 2 b 1 b 2 c 1 c 2 # (with newlines instead of spaces)
DESCRIPTION
The cross operator X
returns the Cartesian product of two or more lists, which means that it returns all possible tuples where the first item is an item of the first list, the second item is an item of second list etc.
If an operator follows the X
, then this operator is applied to all tuple items, and the result is returned instead. So 1, 2 X+ 3, 6
will return the values 1+3, 1+6, 2+3, 2+6
(evaluated as 4, 7, 5, 8
of course).
MOTIVATION
It's quite common that one has to iterate over all possible combinations of two or more lists, and the cross operator can condense that into a single iteration, thus simplifying programs and using up one less indentation level.
The usage as a meta operator can sometimes eliminate the loops altogether.