This page is no longer maintained — Please continue to the home page at www.scala-lang.org

What’s a good and functional way to swap collection elem ents in Scala?

1 reply
Andreas Eisele
Joined: 2010-07-26,
User offline. Last seen 42 years 45 weeks ago.

Hi!

In a project of mine one common use case keeps coming up. At some point
I've got a sorted collection of some kind (List, Seq, etc... doesn't
matter) and one element of this collection. What I want to do is to swap
the given element with it's following element (if this element exists) or
at some times with the preceding element.

I'm well aware of the ways to achieve this using procedural programming
techniques. My question is what would be a good way to solve the problem
by means of functional programming (in Scala)?

Thanks

a. e

Jesper Nordenberg
Joined: 2008-12-27,
User offline. Last seen 42 years 45 weeks ago.
Re: What’s a good and functional way to swap collection elem ent

Andreas Eisele skrev 2010-07-26 16:22:
> In a project of mine one common use case keeps coming up. At some point
> I've got a sorted collection of some kind (List, Seq, etc... doesn't
> matter) and one element of this collection. What I want to do is to swap
> the given element with it's following element (if this element exists) or
> at some times with the preceding element.
>
> I'm well aware of the ways to achieve this using procedural programming
> techniques. My question is what would be a good way to solve the problem
> by means of functional programming (in Scala)?

def swapElems[T](s : Seq[T], elem : T, before : Boolean) = {
val i = s.indexOf(elem)

if (before)
s.patch(i - 1, elem :: s(i - 1) :: Nil, 2)
else
s.patch(i, s(i + 1) :: elem :: Nil, 2)
}

/Jesper Nordenberg

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland