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
  • 25,419
  • 17
  • 47
  • 88
Quentin Geff
  • 819
  • 1
  • 6
  • 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
  • 21,985
  • 6
  • 54
  • 76
6

Try

val xs = List("a","b","c","d")
(xs, xs.tail).zipped.map(_ ++ _) // List(ab, bc, cd)
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
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
  • 25,419
  • 17
  • 47
  • 88