Join elem with next one in a functional style

删除回忆录丶 提交于 2020-01-04 14:05:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!