Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

[src/core/Cool-str.pm] 500% speedup of .trans

Keep a hash with the next index of each substring to be substituted,
and then pick the smallest one through each iteration. (Or, more
informally, "skip the boring parts".) This makes the number of
iterations through the main loop proportional to the number of
substitutions actually made.
  • Loading branch information...
commit 2c66f9a19607046e4d6ceffbbfb7b47710286c2f 1 parent 690e370
@masak masak authored
Showing with 10 additions and 34 deletions.
  1. +10 −34 src/core/Cool-str.pm
View
44 src/core/Cool-str.pm
@@ -176,12 +176,10 @@ augment class Cool {
}
my %c;
- my %prefixes;
for (@changes) -> $p {
die "$p.perl is not a Pair" unless $p ~~ Pair;
my @from = expand $p.key;
my @to = expand $p.value;
-# warn "Substitution is longer than pattern\n" if @to > @from;
if @to {
@to = @to xx ceiling(@from / @to);
} else {
@@ -189,46 +187,24 @@ augment class Cool {
}
for @from Z @to -> $f, $t {
if %c.exists($f) && %c{$f} ne $t {
-# warn "Ambiguous transliteration rule for '$f'; "
-# ~ "using the first one (transliteration to '$t')";
} else {
- if $f.chars > 1 {
- %prefixes{$f.substr(0, 1)} //= [];
- %prefixes{$f.substr(0, 1)}.push($f);
- }
%c{$f} = $t;
}
}
}
- # should be replaced by a proper trie implementation
- # at some point
- for %prefixes.keys {
- %prefixes{$_}.=sort({-.chars});
+ my $i = 0;
+ my $r = "";
+ my %h = %c.keys Z=> map { self.index($_) // Inf }, %c.keys;
+ while ($_ = %h.pairs.sort({-.chars}).min: *.value).value < Inf {
+ %h{.key} = self.index(.key, .value + 1) // Inf;
+ next if .value < $i;
+ $r ~= self.substr($i, .value - $i) ~ %c{.key};
+ $i = .value + .key.chars;
}
+ $r ~= self.substr($i);
- my @res;
- my $l = $.chars;
- loop (my $i = 0; $i < $l; ++$i) {
- my $c = $.substr($i, 1);
- my $success = 0;
- if %prefixes.exists($c) {
- for %prefixes{$c}.list {
- if self.substr($i, .chars) eq $_ {
- @res.push: %c{$_};
- $success = 1;
- $i += .chars - 1;
- last;
- }
- }
- }
- unless $success {
- @res.push: %c.exists($c)
- ?? %c{$c}
- !! $c;
- }
- }
- @res.join: '';
+ return $r;
}
Please sign in to comment.
Something went wrong with that request. Please try again.