[erlang-questions] Strings as Lists

Matthias Lang <>
Fri Feb 15 21:54:00 CET 2008


David Mercer writes:
 > Out of curiosity, besides as an academic exercise and a point of debate,
 > what is the practical use of reversing a string?  I've been programming for
 > a quarter century and am having trouble remembering when I last needed to
 > reverse a string.  Search? yes; compare? yes; substitute? yes; modify? yes.
 > Just can't think of when I've needed to reverse a string.  Is there some
 > common protocol that requires you to send Unicode strings in reverse order
 > or something?

Many tail-recursive algorithms produce reversed lists, so you need
lists:reverse/1 to put them back again at the end. Typical example:

  to_upper(List) ->
    Rev = to_upper(List, []),
    lists:reverse(Rev).

  to_upper([H|T], Acc) ->
    to_upper(T, [H band bnot 16#20|Acc]);
  to_upper([], Acc) ->
    Acc.

Yes, there are other ways of writing to_upper/1.
Yes, I could have put a guard on it.
Yes, I can hear the non-ASCII people grinding their teeth over the band bnot
No, the lists:reverse/1 does not change the big O 

Matt



More information about the erlang-questions mailing list