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.
4 comments:
What kind of lists do you mean to be distinguishing from?
lists:flatten([1,2,3]) == [1,2,3]
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].
[x,y,z]
2> lists:flatten(C) == C.
true
3> D = [1, 2, {3, 4, 5}].
[1,2,{3,4,5}]
4> lists:flatten(D) == D.
true
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.
Justin,
I meant to say if it was a list of strings. I should have updated the blog. Will do that right away.
Steve,
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.
Post a Comment