Created
April 26, 2011 19:03
-
-
Save masak/942868 to your computer and use it in GitHub Desktop.
Lagging for loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sandy,grocery store,tomatoes | |
Sandy,grocery store,cheese | |
Sandy,train station,tickets | |
Ben,train station,tickets | |
Ben,video game store,portal II |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
given open('input') { | |
my @shop-list; | |
my ($last-seen-person, $last-seen-shop); | |
for .lines -> $line { | |
my ($person, $shop, $item) = $line.split(','); | |
if $person ne $last-seen-person || $shop ne $last-seen-shop { | |
if defined $last-seen-shop { | |
push @shop-list, $last-seen-shop; | |
} | |
$last-seen-shop = $shop; | |
} | |
if $person ne $last-seen-person { | |
if defined $last-seen-person { | |
say ($last-seen-person => @shop-list).perl; | |
} | |
@shop-list = (); | |
$last-seen-person = $person; | |
} | |
} | |
if defined $last-seen-shop { | |
push @shop-list, $last-seen-shop; | |
} | |
if defined $last-seen-person { | |
say ($last-seen-person => @shop-list).perl; | |
} | |
.close; | |
} | |
# Problems with the above code: | |
# | |
# A. Two variables whose only purpose is to keep enough lagging state. | |
# B. Tricky conditionals involving these variables. | |
# C. Duplicated code outside of the loop. | |
# D. The `@shop-list` variable needs to have a scope outside of the loop. | |
# E. Lots of accidental complexity due to A-D. | |
# F. Easy to get things wrong due to E. | |
# What I'd like to be able to write: | |
# | |
# given open('input') { | |
# for .lines -> $line { | |
# my ($person, $shop, $item) = $line.split(','); | |
# OVER $person { | |
# my @shop-list; | |
# OVER $shop { | |
# push @shop-list, $shop; | |
# } | |
# say ($person, @shop-list).perl; | |
# } | |
# } | |
# .close; | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment