问题
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?
回答1:
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}
回答2:
Try
val xs = List("a","b","c","d")
(xs, xs.tail).zipped.map(_ ++ _) // List(ab, bc, cd)
回答3:
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
来源:https://stackoverflow.com/questions/55751657/join-elem-with-next-one-in-a-functional-style