2

I'm trying to find a way to "join"/"groupby" 2 elements in a list as following :

List("a","b","c","d")  -> List("ab","bc","cd")

With a functional style.

Would someone know how to do this?

Need I use reducer, fold, scan, other higher-order function?

Andronicus
  • 24,333
  • 17
  • 47
  • 82
Quentin Geff
  • 739
  • 1
  • 5
  • 21

3 Answers3

9

Sliding creates subcollections with sliding window, then you just need to map this sublists to strings:

List("a","b","c","d").sliding(2,1).map{case List(a,b) => a+b}
Krzysztof Atłasik
  • 20,861
  • 6
  • 47
  • 70
6

Try

val xs = List("a","b","c","d")
(xs, xs.tail).zipped.map(_ ++ _) // List(ab, bc, cd)
Dmytro Mitin
  • 37,305
  • 2
  • 20
  • 53
4

You can use sliding to create a window:

val l = List("a","b","c","d")
val res = l.sliding(2).map(_.reduce(_ + _))
res.foreach(println)

this results with

ab
bc
cd
Andronicus
  • 24,333
  • 17
  • 47
  • 82