Skip to content

Instantly share code, notes, and snippets.

@kidd
Created June 3, 2010 23:37
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 kidd/424674 to your computer and use it in GitHub Desktop.
Save kidd/424674 to your computer and use it in GitHub Desktop.
use v6;
use Test;
use MONKEY_TYPING;
augment class Str {
method trans(*@patterns) {
my %replacements;
my @pat;
for @patterns -> $pair {
#null string on the right
if $pair.value.comb.elems == 0 {
for $pair.key.comb -> $a
{
@pat.push($a, Mu);
}
next;
}
#smaller right string
elsif $pair.key.comb.elems > $pair.value.comb.elems {
$pair.value ~= $pair.value.comb[-1] x
($pair.key.comb.elems - $pair.value.comb.elems);
}
#http://irclog.perlgeek.de/perl6/2010-06-03#i_2400803 workaround
@pat.push( (eager $pair.key.comb) Z $pair.value.comb);
}
%replacements = @pat ;
say %replacements.perl ;
my $res = '';
for self.comb -> $char {
if %replacements.exists($char) {
#say $char;
$res ~= %replacements{$char} if %replacements{$char}.defined;
}
else { $res ~= $char }
}
#say $res;
return $res;
#'wrong return value';
}
}
plan *;
is("ABC".trans( ('A'=>'a'), ('B'=>'b'), ('C'=>'c') ),
"abc",
"Each side can be individual characters");
is("XYZ".trans( ('XYZ' => 'xyz') ),
"xyz",
"The two sides of the any pair can be strings interpreted as tr/// would multichar");
is("XYa".trans( ('XYZ' => 'xyz') ),
"xya",
"Not all chars match");
is("abc".trans( ("abc" => "AB") ),
"ABB",
"Right hand too short");
is("abcd".trans( ("abc" => "") ),
"d",
"No right hand");
is("eabcd".trans( ("abc" => "") , ('e'=>'E')),
"Ed",
"No right hand in multiple pairs");
is("abcd".trans( ("abc" => "ABZ"), ('c' => 'C') ),
"ABCd",
"overlapping transliterations");
#...
# ranges should use the flipflop operator?
# using arrays isn't done yet.
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment