This script implements it. Unfortunately, Rakudo does not yet support variable interpolation in strings, so I can't test the script. Also I'm suspicious I have mucked up the combination of
any
and grep
, but it's hard to be sure without testing the script.
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
use v6; | |
my %dictionary; | |
slurp("big.txt").comb(/<alpha>+/).map({%dictionary{$_.lc}++}); | |
sub edits($word) { | |
my @s = (^$word.chars).map({$word.substr(0, $_), $word.substr($_)}); | |
my @deletes = @s.map(-> $a, $b { $a ~ $b.substr(1); }); | |
my @transposes = @s.map(-> $a, $b { $a ~ $b.substr(0, 2).flip ~ $b.substr(2) if $b.chars > 1 }); | |
my @replaces = @s.map(-> $a, $b {$a ~ ':' ~ $b.substr(1)}); | |
my @inserts = (@s,$word,"").map(-> $a, $b {$a ~ ':' ~ $b}); | |
return (@deletes, @transposes, @replaces, @inserts); | |
} | |
sub edit_list_to_regex(@el) { | |
any(@el.uniq>>.subst(':', '<alpha>', :g).map({ rx/ ^ $_ $ / })); | |
} | |
sub correct($word) { | |
return $word if (%dictionary{$word}); | |
my $regex = edit_list_to_regex(edits($word)); | |
my @candidates = %dictionary.keys.grep($regex); | |
if @candidates.elems == 0 { | |
$regex = edit_list_to_regex(edits($word).map({edits($_)})); | |
@candidates = %dictionary.keys.grep($regex); | |
} | |
return @candidates.max({%dictionary{$_} // 0}); | |
} | |
correct("lary").say; |
Anyway, for those of you keeping score at home, Norvig's original Python script does this task in 21 lines of code. This quasi-correct Perl 6 version adds full Unicode support with just an additional 3 lines of code, for 24 total. And that's counting 4 lines which are just
}
, and the semi-optional use v6;
line as well. Assuming fixing the issues don't require additional lines, this looks like a clear win for Perl 6. And I'm quite sure this code can be made a good bit better and clearer...
No comments:
Post a Comment