Last active
April 12, 2018 13:07
-
-
Save JaHIY/c8e0f4ba4bb6e944b985393d61711a91 to your computer and use it in GitHub Desktop.
Soundex algorithm in Erlang
This file contains hidden or 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
#!/usr/bin/env escript | |
%% -*- erlang -*- | |
%%! -smp enable -sname soundex -mnesia debug verbose | |
main([String]) -> | |
Word = soundex(String), | |
io:format("~s => ~s\n", [String, Word]); | |
main(_) -> | |
usage(). | |
usage() -> | |
io:format("usage: soundex string\n"), | |
halt(1). | |
soundex(L) when is_list(L) -> | |
soundex(L, 4). | |
soundex([H|T], Length) -> | |
Len = Length - 1, | |
if | |
H >= $A, H =< $Z -> | |
[H|soundex1(T, Len)]; | |
H >= $a, H =< $z -> | |
N = H - ($a - $A), | |
[N|soundex1(T, Len)]; | |
true -> | |
soundex(T) | |
end; | |
soundex([], _) -> | |
[]. | |
soundex1(L, Length) when is_list(L) -> | |
Result = soundex1(L, "?", Length), | |
Diff = Length - length(Result), | |
if | |
Diff > 0 -> | |
Result ++ lists:duplicate(Diff, $0); | |
true -> | |
Result | |
end. | |
soundex1([H|T], PrevChar, Length) when Length > 0 -> | |
if | |
H >= $A, H =< $Z -> | |
SoundexMap = #{ | |
$A => $0, | |
$B => $1, | |
$C => $2, | |
$D => $3, | |
$E => $0, | |
$F => $1, | |
$G => $2, | |
$H => $0, | |
$I => $0, | |
$J => $2, | |
$K => $2, | |
$L => $4, | |
$M => $5, | |
$N => $5, | |
$O => $0, | |
$P => $1, | |
$Q => $2, | |
$R => $6, | |
$S => $2, | |
$T => $3, | |
$U => $0, | |
$V => $1, | |
$W => $0, | |
$X => $2, | |
$Y => $0, | |
$Z => $2 | |
}, | |
Char = maps:get(H, SoundexMap), | |
if | |
Char =/= PrevChar, Char =/= $0 -> | |
[Char|soundex1(T, Char, Length-1)]; | |
true -> | |
soundex1(T, PrevChar, Length) | |
end; | |
H >= $a, H =< $z -> | |
N = H - ($a - $A), | |
soundex1([N|T], PrevChar, Length); | |
true -> | |
soundex1(T, PrevChar, Length) | |
end; | |
soundex1(_, _, Length) when Length =< 0 -> | |
[]; | |
soundex1([], _, _) -> | |
[]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment