[erlang-questions] Strings as Lists
Fri Feb 15 21:45:45 CET 2008
David Mercer wrote:
> 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?
When you need to do a manipulation on string in constant length,
you need reverse. For example, to_upper() can be implemented as
to_upper(L) = foldr(fun(C, A) -> [char_upper(C) | A] end, , L).
to_upper(L) = map(fun char_upper/1, L).
of which both both have O(n) space requirement, or via
to_upper(L) = lists:reverse(to_upper(L, ))
to_upper(, Acc) -> Acc;
to_upper([C|T], Acc) -> to_upper(T, [char_upper(T)|Acc]).
which is O(n) in space.
Both are O(n) in time, though with different coefficients.
More information about the erlang-questions