【问题标题】:Scalaz splitting a computation into sub-partsScalaz 将计算拆分为子部分
【发布时间】:2011-02-19 11:29:27
【问题描述】:

我有一个很大的List[A] 和一个函数f: List[A] => List[B]。我想将我的原始列表拆分成最大大小的子列表,依次将函数应用到每个子列表,然后unsplit将结果变成一个大List[B] .这很容易:

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(_)))
}

我想知道 scalaz 是否提供了开箱即用的标准东西?特别是apply 方法?

【问题讨论】:

    标签: scala functional-programming scalaz


    【解决方案1】:

    unsplit 只是MA#join,对于任何M[M[A]],其中MMonad

    split 不存在开箱即用。下面是一轮关于这样做的方式,更多的是为了演示一些Scalaz的概念。它实际上在此刻触发了编译器中的堆栈溢出!

    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
    

    【讨论】:

    • 问题是我的fM[A] => M[B]:我在scalaz 中没有看到任何可以帮助解决这个问题的东西(我只看到A => M[B]M[A => B] 等)
    • val f: List[A] => List[B] = ...; (grouped map f join): List[B]
    【解决方案2】:

    这个怎么样:

    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)
    

    【讨论】:

    • 嗯,嗯,是的。我说这很容易——我问 Scalaz 是否有任何东西可以开箱即用地实现这一点(可能比其他 monad 更普遍)
    • 我想说 ls.grouped(max) 和 split(ls,max) 一样简洁
    猜你喜欢
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 2014-08-11
    • 2018-08-09
    • 2011-05-30
    相关资源
    最近更新 更多