Map

From Syntax

Jump to: navigation, search

Map is an idiom that returns zero or more elements, in place, for each element of a given list.

Grep can be considered a specific form of map that returns either nothing or the same element for each element.

[edit] Perl

my @a = map { $_, $_ + 1 } qw(1 3 5); # @a = (1, 2, 3, 4, 5, 6)
Perl code

[edit] Unraveling map

Some programming languages do not support map, but nearly all support for loops. Here is a paragraph that acts like map, reimplemented using a for loop.

my @a = do {
  my @elements = qw(1 3 5);

  my @stack;
  for (@elements) {
    push @stack, $_, $_ + 1;
  }

  @stack;
};
Personal tools