Skip to content

Instantly share code, notes, and snippets.

@m-2k
Forked from 5HT/dist.erl
Last active September 11, 2015 06:57
Show Gist options
  • Save m-2k/729a1ca975fda7a91bd6 to your computer and use it in GitHub Desktop.
Save m-2k/729a1ca975fda7a91bd6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env escript
-module(dist).
-compile([export_all]).
% optimized combinators
int(true) -> 1;
int(_) -> 0.
rev(L) -> lists:reverse(L).
rtr(L) -> rev(tl(rev(L))).
last(L) -> [lists:last(L)].
htr(L) -> [hd(tl(rev(L)))].
rtt(L) -> rev(tl(tl(rev(L)))).
% Levenshtein distance
dist(A,A) -> 0;
dist(A,[]) -> length(A);
dist([],B) -> length(B);
dist(A,B) -> dist(get({A,B}),A,B).
dist(undefined,A,B) -> dist(1000,A,B);
dist(T,_,_) when T < 1000 -> T;
dist(_,A,B) ->
T2 = lists:min([dist(A,rtr(B)),dist(rtr(A),B),dist(rtr(A),rtr(B))-int(last(A)==last(B))]) + 1,
case length(A)>1 andalso length(B)>1 andalso last(A)==htr(B) andalso htr(A)==last(B) of
true -> lists:min([T2,dist(rtt(A),rtt(B))+1]);
false -> put({A,B},T2),T2 end.
main([A,B]) -> io:format("dist(~p,~p) = ~p~n",[A,B,dist(A,B)]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment