我有一个非常大的List[A]
和一个函数f: List[A] => List[B]
。我想将原始列表拆分为具有最大大小的子列表,依次将该函数应用于每个子列表,然后将 unsplit 结果转换为一个大{{1} }}。这很简单:
List[B]
我想知道 scalaz 是否提供了开箱即用的标准内容?特别是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(_)))
}
方法?
答案 0 :(得分:3)
unsplit
MA#join
为M[M[A]]
的任何M
, Monad
仅为split
。
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
不存在。以下是关于这样做的一个回合,更多的是展示一些Scalaz概念。它实际上会在编译器中触发堆栈溢出!
{{1}}
答案 1 :(得分:1)
这个怎么样:
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)