Skip to content

Instantly share code, notes, and snippets.

@LastOfTheCarelessMen
Created November 1, 2009 17:13
Show Gist options
  • Save LastOfTheCarelessMen/223616 to your computer and use it in GitHub Desktop.
Save LastOfTheCarelessMen/223616 to your computer and use it in GitHub Desktop.
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment