Camelia
Prev: Reversed operators

Hyper Operators

Hyper operators are really interesting. They allow the extrapolation of a scalar operator to operate on a list of scalars.

The real operators are actually unicode characters but using regular doubled angle-brackets also work.

Normally the arrows point inside, towards the operator and there are two lists on the two sides of the operator.

This will apply the regular infix operator to the pairs as taken from the two lists on the two sides and return a list with the same length.

If the list on one side is longer than on the other side perl throws an exception "Non-dwimmy hyperoperator cannot be used on arrays of different sizes or dimensions."

In order to make the operator dwimmy you need to turn the arrows around to point to the operand that should dwim. It can be either or both operands. If an operand is being pointed at (that is if it is supposed to dwim) then in case that operand is too short, perl will automatically use the last value of it repeatadly as long as the other side needs pairs.

You can make both sides dwimmy if you don't know up front which one will be longer and if you want to make them work in both ways.

As a special case if one side is a single scalar and if the arrow points in its direction then that value will be paired with each one of the values from the array on the other side.

examples/arrays/hyper.p6
#!/usr/bin/env perl6
use v6;

my @x = (1, 2) >>+<< (3, 4);
say @x.perl;  # [4, 6]

#my @d = (1, 2) >>+<< (3);
#say @d.perl;  # [4, 6]
# Non-dwimmy hyperoperator cannot be used  on arrays of different sizes or dimensions.

my @z = (1, 2, 3, 4) >>+>> (1, 2);
say @z.perl;      # [2, 4, 5, 6]


@z = (1, 2, 3, 4) <<+>> (1, 2);
say @z.perl;      # [2, 4, 5, 6]

@z = (4) <<+>> (1, 2);
say @z.perl;      # [5, 6]


my @y = (1, 2) >>+>> 1;
say @y.perl;      # [2, 3]

There is a lot more to hyper operators but for now this should be enough.
examples/arrays/hyper.p6.out
Array.new(4, 6)
Array.new(2, 4, 4, 6)
Array.new(2, 4, 4, 6)
Array.new(5, 6)
Array.new(2, 3)

Prev: Reversed operators

Table of Contents

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: