Saturday, December 13, 2008

Differentiate string from regular list in Erlang

Erlang is a great language to work with. I need to concentrate on the business logic rather than nifty details about the distributed computing like communication between nodes, handle node failures, restart apps etc. All these details are already taken care by the language itself. Yes.. distributed computing and concurrent programming is a integrated part of the language.

Erlang implement string in terms of list. So it is tricky to distinguish regular string from the list. For example,

foo(C) when is_string(C) ->
% do something with string;
foo(C) when is_list(C) ->
% do something with list.

First of all there is no function called "is_string" in Erlang. (I just made it up). But the point here is that how to distinguish regular string from the list. I came up with this solution.

foo(C) when lists:flatten(C) == C ->
% do something with string;
foo(C) when is_list(C) ->
% do something with list.

Somewhat inefficient because of call to lists:flatten/1 call. But for small strings, it is not an issue at all.


Justin Sheehy said...

What kind of lists do you mean to be distinguishing from?

lists:flatten([1,2,3]) == [1,2,3]

Steve Vinoski said...

Unfortunately that's not going to help you. You're asserting that a flat list is always a string, which clearly isn't true. For example:

Eshell V5.6.5 (abort with ^G)
1> C = [x, y, z].
2> lists:flatten(C) == C.
3> D = [1, 2, {3, 4, 5}].
4> lists:flatten(D) == D.

The first is a list of atoms, the second a mixed list of integers and a tuple. Both are flat, but neither is a string.

I never run into issues in my Erlang regarding whether something is a string or a list, but I do remember worrying about this when I first started using the language. If you're worrying about this sort of thing, I think you're focusing at too low a level. Perhaps you could supply an example of why this issue is troubling you so others can help you fix it.

Dude From Mangalore said...


I meant to say if it was a list of strings. I should have updated the blog. Will do that right away.

Dude From Mangalore said...


You are correct. Justin also noted the same thing.

I will do a new post on what I am trying to solve with this.

Thanx for noticing the bug in the example I posted.

Book Promotion