[erlang-questions] Replace list element

Ulf Wiger <>
Fri May 27 08:46:56 CEST 2011


On 26 May 2011, at 16:26, Alexander Kuleshov wrote:

> Hello,
> 
> How can i fast replace 2 elements in Erlang list? For example I have
> list: [1,2,3,4], how can i quickly get [1,3,2,4]?

From your example, I read the question as "How can I *swap* 2 elements in an Erlang list?"

swap([X, Y | T], X, Y) ->
    [Y, X | T];
swap([H | T], X, Y) ->
    [H | swap(T, X, Y)].

Decisions to be made include:

- swap every instance or just the first pair?
- what to do at the end of the list (do we require that there should be at least one matching pair?)

I think this is a fairly good example of the kind of operation that, while seemingly generic, is not a particularly good candidate for a library function; it's so easy to implement with the exact semantics you require for your problem, and there *are* possible variants.

BR,
Ulf W

Ulf Wiger, CTO, Erlang Solutions, Ltd.
http://erlang-solutions.com



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20110527/d99fd7e1/attachment.html>


More information about the erlang-questions mailing list