簡體   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