Longest common prefix: Difference between revisions

→‎{{header|Erlang}}: Added erlang example
(→‎{{header|Erlang}}: Added erlang example)
Line 669:
lcp(["prefix", "suffix"]) = ""
lcp(["foo", "foobar"]) = "foo"
</pre>
 
 
=={{header|Erlang}}==
 
A bow to the perversion of the Scala implementation. Not canonical erlang, this.
 
{{trans|Scala}}
 
<lang erlang>
 
-module(lcp).
-export([ main/1 ]).
shortest(List,Size) when length(List) =:= 0 ->
Size;
 
shortest(List,Size) ->
[H|T] = List,
if
length(H) < Size ->
shortest(T, length(H) );
true ->
shortest(T, Size )
end.
 
uniq(List, Size ) ->
First = string:substr(hd(List),1,Size),
Last = string:substr(lists:last(List),1,Size),
Ttuples = lists:zip(First, Last),
% this is the bit that is like the scala version
TheList = lists:takewhile(
fun(E) ->
case element(1,E) =:= element(2,E) of true -> true;
_ -> false
end
end, Ttuples),
Prefix = length(TheList),
io:format("Prefix: ~p~n", [string:substr(First,1,Prefix)]).
main(List) ->
Sorted = lists:sort(List),
if
length(List) < 2 ->
io:format("Prefix empty:$~p~n",[List]);
true ->
Size = length(hd(List)),
uniq(Sorted, shortest(Sorted,Size))
end.
 
 
</lang>
{{out}}
<pre>
47> lcp:main(["interspecies","interstellar","interstate"]).
Prefix: "inters"
ok
 
 
</pre>
 
Anonymous user