Skip to content

Instantly share code, notes, and snippets.

@colomon
Created October 23, 2009 20:07
Show Gist options
  • Select an option

  • Save colomon/217159 to your computer and use it in GitHub Desktop.

Select an option

Save colomon/217159 to your computer and use it in GitHub Desktop.
use v6;
my %dictionary;
slurp("big.txt").comb(/<alpha>+/).map({%dictionary{$_.lc}++});
my @alphabet = 'a'..'z';
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 { @alphabet.map({$a ~ $_ ~ $b.substr(1)}) });
my @inserts = (@s,$word,"").map(-> $a, $b { @alphabet.map({$a ~ $_ ~ $b})});
return (@deletes, @transposes, @replaces, @inserts);
}
sub correct($word) {
return $word if (%dictionary{$word});
my @candidates = edits($word).grep({ %dictionary{$_} });
# @candidates = edits($word).map({ edits($_) }).grep({ %dictionary{$_} }) if @candidates.elems == 0;
return $word if @candidates.elems == 0;
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