Distinguishing Strings from Lists in Erlang

07/24/2009

One of the issues I run into every couple of weeks with Erlang is distinguishing lists from strings. This is made complicated because strings are merely a list of integers. That said, running with that definition, there is a very simple solution.

is_string(X) ->
    lists:foldl(fun(N,Acc) ->
                         case Acc of
                             false ->
                                 false;
                             true ->
                                 is_integer(N)
                         end end, true, X).

Admittedly, not an efficient solution. You could wrap it in a try-catch block and use a throw to exit the loop upon reaching the first non-integer, but the worst-case efficiency remains O(N). Any suggestions on how to improve?

All Rights Reserved, Will Larson 2007 - 2014.