develooper Front page | perl.perl6.users | Postings from April 2020

Re: unflattering flat

Thread Previous | Thread Next
From:
Elizabeth Mattijsen
Date:
April 4, 2020 07:54
Subject:
Re: unflattering flat
Message ID:
8FB0100A-C3CC-4E54-BF63-DCDB91BB1B16@dijkmat.nl
> On 2 Apr 2020, at 23:49, Konrad Bucheli via perl6-users <perl6-users@perl.org> wrote:
> I have a hash with arrays as value. Out of that I wanted to get a flat list with all the entries in the value arrays. My first intuitive attempt was to use flat, but somehow that only works with an additional map step:
> 
> $ raku
> To exit type 'exit' or '^D'
>> my %hash-with-arrays = a => [1,2], b => [2,3]
> {a => [1 2], b => [2 3]}
>> %hash-with-arrays.values.flat
> ([2 3] [1 2])
>> %hash-with-arrays.values>>.map({$_})
> ((2 3) (1 2))
>> %hash-with-arrays.values>>.map({$_}).flat
> (2 3 1 2)
>> 
> $ raku -v
> This is Rakudo version 2020.02 built on MoarVM version 2020.02
> implementing Raku 6.d.
> $ 
> 
> How is that explained?

This is because the array inside the hash is inside a container.  You can see this is you use `dd` to show the contents of a key:

> dd %hash-with-arrays<a>
Array %hash-with-arrays = $[1, 2]

Note the $ prefix in the output.  This inhibits automatic iteration of the array.  There is a simple way around it:

> %h.values.map: |*
(1 2 2 3)

This slightly line-noisy solution is short for:

> %h.values.map( { $_.Slip } )
(1 2 2 3)

Aka, "slip" the values into a single stream of values, hence getting the result you wanted
Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About