Skip to content

Instantly share code, notes, and snippets.

@masak
Created April 26, 2011 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/942868 to your computer and use it in GitHub Desktop.
Save masak/942868 to your computer and use it in GitHub Desktop.
Lagging for loops
Sandy,grocery store,tomatoes
Sandy,grocery store,cheese
Sandy,train station,tickets
Ben,train station,tickets
Ben,video game store,portal II
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