开发者

Scalaz splitting a computation into sub-parts

开发者 https://www.devze.com 2022-12-30 20:28 出处:网络
I have a very large List[A] and a function f: List[A] => List[B]. I would like to split my original list into sub-lists with a maximum size, apply the function to each sublist in turn and then unsp

I have a very large List[A] and a function f: List[A] => List[B]. I would like to split my original list into sub-lists with a maximum size, apply the function to each sublist in turn and then unsplit the result into one big List[B]. This 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 whether scalaz supplied standard stuff to do this out开发者_运维问答 of the box? In particular the apply method?


unsplit it just MA#join, for any M[M[A]] where M is a Monad.

split doesn't exist out of the box. The following is a round about way of doing this, more to demonstrate some Scalaz concepts. It actually triggers a stack overflow in the compiler at the moment!

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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号