![](/img/trans.png)
[英]Applicative Functor instance for functions with the same result type in Scala
[英]Applicative instance for ZipList in Scala
這是一個后續一個我最近的以前的問題:
我想為List
(可能還有Set
和Map
)定義一個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.