From:

Date:

February 10, 2019 18:05Subject:

Re: list comprehensionMessage ID:

CAD2L-T0js0RyYmnwq4x+EaQYNiDS-zZGC92uGERhjpuKYAwqOg@mail.gmail.comIn {l for l in L} The reason it is in `{}` is to create a Set from iterating over `L`. > In Python, the set-builder's braces are replaced with square brackets, parentheses, or curly braces, giving list, generator, and set objects, respectively. So in Python: [ l for l in L ] gives a list ( l for l in L ) gives a generator { l for l in L } gives a set In Perl6 those would most likely be written as: L.List or L.Array or L.list L.Seq L.Set --- The way to do that is my \L = ((1..10) xx 3).flat.pick(*).list; set( L ) # A L.Set # B my %set is SetHash; { ++%set{$_} for L } # C # D do { # add the {} syntax to create a Set (lexically) my sub circumfix:«{ }» ( \L ) { L.Set }; { $_ for L } # <-- } Something that seems similar to me is `unique` .say for L.unique; By that I mean, some places where you would use a Set, it makes sense to use `.unique` instead --- As for `{(k, x) for k in K for x in X if P(x)}` The easiest one to directly translate appears to be the Scala one my \K = 1..10; my \X = 5..15; # for (k <- K; x <- X if P(x)) yield (k,x) Set.new: gather { for K -> \k { for X -> \x { if P(x) { take (k,x); } } } } Other ways: Set.new: (K X[,] X).grep: -> ( \k, \x ) { P(x) } Set.new: K X[,] X.grep: &P Set.new: K X[,] X.grep: &P Set.new: ( -> ( \k, \x ) { (k,x) if P(x) } for K X[,] X ) Set.new: ( -> \x { |(-> \k { (k,x) if P x } for K) } for X) On Sun, Feb 10, 2019 at 10:26 AM mimosinnet <mimosinnet@gmail.com> wrote: > > Hi all, > > I wonder what would be the Perl notation for 'set-builders', as exposed > in this wikipedia article: > > https://en.wikipedia.org/wiki/Set-builder_notation#Parallels_in_programming_languages > > This is the Python notation: > > Example 1: {l for l in L} > Example 2: {(k, x) for k in K for x in X if P(x)} > > This is another example in Python: > > s = {v for v in 'ABCDABCD' if v not in 'CB'} > > https://en.wikipedia.org/wiki/List_comprehension#Similar_constructs > > I have been playing with the code below. Nevertheless, I am unsure on > how to use the code to define a set. > > Cheers! > > <--- Code > #!/usr/bin/env perl6 > > my @L = 1 .. 10; > my @K = 1 .. 10; > my @X = 5 .. 15; > > say "Example 1:"; > for @L -> $l { > print "$l " if $l ∈ @L; > } > > say "\nExample 2:"; > for @K -> $k { for @X -> $x { > print "($k, $x), " if ($k ∈ @K and $x ∈ @X and $x < 8); > }} > <--- > > -- > (≧∇≦) Mimosinnet (Linux User: #463211)Thread Previous | Thread Next

- list comprehension by mimosinnet
- Re: list comprehension by Lucas Buchala
- Re: list comprehension by Brian Duggan
**Re: list comprehension**by Brad Gilbert- Re: list comprehension by mimosinnet
- Re: list comprehension by Brad Gilbert
- Re: list comprehension by =?utf-8?B?Sm9hbiBQdWpvbCBUYXJyw6lz?=

nntp.perl.org: Perl Programming lists via nntp and http.

Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About