Scalaz splits computation into parts

I have a very large List[A]

and function f: List[A] => List[B]

. I would like to split my original list into max-sized sub-lists, apply the function to each sub-list in turn, and then expand the result into one large one List[B]

. It's pretty easy:

def split[T](l : List[T], max : Int) : List[List[T]] = //TODO

def unsplit[T](l : List[List[T]]) : List[T] = //TODO

def apply[A, B](l : List[A], f : List[A] => List[B], max : Int) : List[B] = {
  unsplit(split(l, max).map(f(_)))
}

      

I was wondering if scalaz supplied the standard stuff to do this out of the box? In particular, the method apply

?

+2


a source to share


2 answers


unsplit

it's easy MA#join

for anyone M[M[A]]

where it M

is Monad

.

split

doesn't exist out of the box. Below is an example on how to do this to demonstrate some of the Scalaz concepts. This is actually causing a stack overflow in the compiler for now!



val ls = List(1, 2, 3, 4, 5)
val n = 5

def truesAndFalses(n: Int): Stream[Boolean] = 
  Stream.continually(true.replicate[Stream](n) |+| false.replicate[Stream](n)).join

val grouped: List[List[Int]] = {
  var zipped: List[(Int, Boolean)] = ls.zip(truesAndFalses(2))
  var groupedWithBools: List[List[(Int, Boolean)]] = zipped splitWith {_._2}
  groupedWithBools ∘∘ {pair: (Int, _) => pair._1}
}

val joined: List[Int] = grouped ∘∘ {_ * 2} join

      

+3


a source


How about this:



def split[T](ls: List[T],max: Int): List[List[T]] = ls.grouped(max).toList

def unsplit[T](ls: List[List[T]]): List[T] = ls.flatMap(identity)

      

+1


a source







All Articles