Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^6: in search of a more elegant if then else

by TimToady (Parson)
on Feb 20, 2010 at 18:13 UTC ( [id://824412]=note: print w/replies, xml ) Need Help??


in reply to Re^5: in search of a more elegant if then else
in thread in search of a more elegant if then else

Yes, that's more or less a list comprehension syntax. To make it a bit more concrete, let's suppose you only want unequal chars; you could do it any of these ways in Perl 6:
my @filtered = grep { .[0] ne .[1] }, do [ $0, $1 ] while $s ~~ m:g[(. +)(.)]; my @filtered = do [ $0, $1 ] if $0 ne $1 while $s ~~ m:g[(.)(.)]; my @filtered = ([ $0, $1 ] if $0 ne $1 for $s.comb(/(.)(.)/)); my @filtered = map -> $a, $b {[ $a, $b ] if $a ne $b }, $s.comb;
We get list comprehensions more or less for free in Perl 6 because loops are basically just maps in disguise, and because we allow conditional modifiers inside of looping modifiers. That modifier nesting is something that Perl 5 could easily steal back from Perl 6, even if the loop doesn't automatically return its values.

Replies are listed 'Best First'.
Re^7: in search of a more elegant if then else
by BrowserUk (Patriarch) on Feb 21, 2010 at 00:22 UTC

    Out of interest, do you have a preference amongst those 4?


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      I have a vague preference for the last one, but only because it's most like how I'd actually write it:
      my @filtered = do for $s.comb -> $a, $b { [ $a, $b ] if $a ne $b; }
      or maybe slightly clearer would be:
      my @filtered = gather for $s.comb -> $a, $b { take [ $a, $b ] if $a ne $b; }
      But mathematicians are likely to prefer the list comprehension syntax, I suspect.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://824412]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-03-28 18:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found