Documentation for method flatmap

Documentation for method flatmap, assembled from the following types:

class Any

From Any

(Any) method flatmap

Defined As:

method flatmap(Any:U: &code --> Seq)

Treats the Any as 1-item list and uses List.flatmap on it.

say Any.flatmap({.reverse}); # OUTPUT: «((Any))␤» 

class List

From List

(List) method flatmap

Defined as:

method flatmap(List:D: &code --> Seq:D)

Like map iterates over the elements of the invocant list, feeding each element in turn to the code reference, and assembling the return values from these invocations in a result list.

The use of flatmap is strongly discouraged. Instead of .flatmap( ), please use .map( ).flat as it is clear when the .flat is called and is not confusing like .flatmap.

Unlike map it flattens non-itemized lists and arrays, so

## flatmap 
my @list = ('first1', ('second2', ('third3''third4'), 'second5'), 'first6');
say @list.flatmap({.reverse}).perl;
# OUTPUT «("first1", "second5", "third3", "third4", "second2", "first6").Seq␤» 
## map 
say @list.map({"$_ was a {.^name}"}).perl;
# OUTPUT «("first1 was a Str", "second2 third3 third4 second5 was a List", "first6 was a Str").Seq␤» 
## .map .flat has the same output as .flatmap 
say @list.map({.reverse}).flat.perl
# OUTPUT «("first1", "second5", "third3", "third4", "second2", "first6").Seq␤»