- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Whats a good and functional way to swap collection elem ents in Scala?
Mon, 2010-07-26, 15:22
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
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