繁体   English   中英

Scala中ZipList的适用实例

[英]Applicative instance for ZipList in Scala

这是一个后续一个我最近的以前的问题:

我想为List (可能还有SetMap )定义一个zip Applicative实例。 例如:

val xs: List[Int] = List(1, 2, 3)
val fs: List[Int => Int] = List(f1, f2, f3)
val ys: List[Int] = xs <*> fs // expected to be List(f1(1), f2(2), f3(3))

所以我定义了一个ZipList及其Applicative

case class ZipList[A](val list: List[A])

implicit val zipListApplicative = new Applicative[ZipList] {

  def point[A](a: => A): ZipList[A] = ZipList(List(a))

  def ap[A, B](za: => ZipList[A])(zf: => ZipList[A => B]): ZipList[B] = {
    val bs = (za.list zip zf.list) map {case (a, f) => f(a)}
    ZipList(bs)
  }
}

并可以如下使用它:

 scala> val xs: List[Int] = List(1, 2, 3)
 xs: List[Int] = List(1, 2, 3)

 scala> val fs: List[Int => Int] = List(_ + 2, _ + 2, _ +1)
 fs: List[Int => Int] = List(<function1>, <function1>, <function1>)

 scala> ZipList(xs) <*> ZipList(fs)
 res4: ZipList[Int] = ZipList(List(3, 4, 4))

它似乎正在工作,但也许我缺少一些东西。

  • zipListApplicative是否符合适用法律?
  • ZipList是否应该是一个流,因为该point应该生成一个无限的值流? 为什么呢

申请人应符合法律

point identity <*> v == v

你没有的

point identity List(1,2,3) == List(1)

pure a的拉链名单应该返回的无限流a这就是为什么你需要一个懒惰的数据结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM