Skip to content

Instantly share code, notes, and snippets.

@sekia
Created August 17, 2015 07:21
Show Gist options
  • Select an option

  • Save sekia/07ad09770b3ecce5136c to your computer and use it in GitHub Desktop.

Select an option

Save sekia/07ad09770b3ecce5136c to your computer and use it in GitHub Desktop.
Perl 6's list flatten behaviour example
#!/usr/bin/env perl6
# cf. http://pmthium.com/2014/10/apw2014/
# "List assignment and the [ ] array constructor are unchanged; they continue
# to flatten their input elements. (Arrays are naturally flat.)"
my ($a, $b, $c) = 1, (2, 3), (4, 5, 6);
.say for $a, $b, $c; # 1, 2, 3
my $ary = [1, (2, 3), (4, 5, 6)];
say $ary.elems; # 6, not 3
# "for @a,@b { ... } flattens @a,@b and applies the block to each element of
# @a followed by each element of @b"
my @a = ^10;
my @b = 'a' .. 'f';
.say for @a, @b; # '0', .., '9', 'a', .., 'f'
# "Method calls tend to not flatten their invocant."
# "Argument lists continue to depend on the context in which they are bound:
# ..."
# "The above two points produce a general guideline that method call invocants
# are generally not-flattened, while function call arguments are more likely
# to be. "
(1, (2, 3), (4, 5, 6)).map({ $_ }).perl.say;
say (map { $_ }, (1, (2, 3), (4, 5, 6))).perl;
my @c = 'A' .. 'F';
# Expected one of three arrays (@a, @b or @c), but the invocant seems to be
# flatten just same as next line.
(@a, @b, @c).pick(1).perl.say;
say (pick 1, @a, @b, @c).perl;
# "The flattening behavior of operators continues to be specific to each
# operator - ..."
# Reduce meta-operator
([,] (1, (2, 3), (4, 5, 6))).perl.say; # (1, 2, 3, 4, 5, 6)
# infix:<xx> operator
((1, (2, 3), (4, 5, 6)) xx 2).perl.say; # ((1, (2, 3), (4, 5, 6)), (...))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment