Generalization of the collection method

If I want to generalize the following method for all types of collections that support all the necessary operations ( foldLeft , flatMap , map and :+ ), then how to do this? Currently, it only works with lists.

code:

 def join[A](lists: List[List[A]]): List[List[A]] = { lists.foldLeft(List(List[A]())) { case (acc, cur) => for { a <- acc c <- cur } yield a :+ c } } 
+4
source share
1 answer

If you only want this for collections that support :+ , the easiest way is to simply define it in terms of Seq instead of List .

You can make this a lot more general, down to Traversable , using collectors. I would be happy to explain that when I have a little more time on my hands, but it tends to get complicated at this level.

The applicative Scalaz functors are probably the way to go, but I will let someone with Scalaz experience than me answer this specific answer.

+2
source

Source: https://habr.com/ru/post/1342477/


All Articles