Problems with Strings

Ulf Wiger <>
Fri Mar 28 15:34:42 CET 2003


On Fri, 28 Mar 2003, Pablo Dejuan wrote:

>After looking at the API more carefully, I realized that to concat two
>strings you should use ++ (I know it's sounds silly but I was confused
>with other languages).
>So I'll rewrite it as:
>inversa("") -> "";
>inversa([A1|A]) -> inversa(A) ++ [A1].

You could do that, but be aware of the fact that append has
O(N) complexity. I some cases, this may not matter, but it's
always good to know.

Lists are represented as "cons" cells. Look upon them as
linked lists (without a "last" pointer). Using ++ to append
is about as expensive as traversing a normal linked list
from start to end each iteration in order to add one
element.

I assume that what you're after is something other than
simply reversing a string (since you can't beat
lists:reverse/1 for that). If you really want to implement
reverse in plain erlang, then this is the most efficient
version:

reverse(List) -> reverse(List, []).
reverse([H|T],Acc) ->
  reverse(T,[H|Acc]);
reverse([], Acc) ->
  Acc.

A few words then on ++

If you use ++ in hard-coded constructs like

 URL = "http://" ++ Location

this is no more expensive than

 URL = [$h,$t,$t,$p,$:,$/,$/|Location]

but some may find it easier to read.

You may also use ++ in pattern matching:

  location("http://" ++ L) ->
     L.

which is equivalent to

  location([$h,$t,$t,$p,$:,$/,$/|L]) -> L.


These constructs yield identical compiled code.

/Uffe
-- 
Ulf Wiger, Senior Specialist,
   / / /   Architecture & Design of Carrier-Class Software
  / / /    Strategic Product & System Management
 / / /     Ericsson AB, Connectivity and Control Nodes




More information about the erlang-questions mailing list