【发布时间】:2016-10-23 22:04:30
【问题描述】:
这是对我之前问题的answer 的后续跟进。
我们知道函子是组合的。我可以像这样使用scalaz 编写函子List[_] 和Option[_] 的组合:
import scalaz._, Scalaz._
scala> val flist = Functor[List]
flist: scalaz.Functor[List] = scalaz.std.ListInstances$$anon$1@a5f0295
scala> val foption = Functor[Option]
foption: scalaz.Functor[Option] = scalaz.std.OptionInstances$$anon$1@51e43ad4
scala> flist compose foption
res0: scalaz.Functor[[α]List[Option[α]]] = scalaz.Functor$$anon$1@94c02b
scala> val f = flist compose foption
f: scalaz.Functor[[α]List[Option[α]]] = scalaz.Functor$$anon$1@610bffa0
scala> val os: List[Option[Int]] = Some(1) :: Some(2) :: None :: Nil
os: List[Option[Int]] = List(Some(1), Some(2), None)
scala> f.map(os) {_ + 1}
res1: List[Option[Int]] = List(Some(2), Some(3), None)
用scalaz 组合函子是正确的方法吗?
你能给出一个函子组合的现实生活例子吗?
【问题讨论】:
-
你不重复你现有的问题吗? stackoverflow.com/questions/31284131/…
-
部分。我现在知道如何组合函子了。顺便说一句,谢谢你的回答:) 现在我对 real-life 仿函数组合的例子很感兴趣。
-
在列表中映射选项还不够好吗?
-
不 :) 我需要更多...
-
仿函数是一种抽象,它的层次太高,无法给出任何有趣的例子(不同于简单的嵌套列表/选项等)。这就像在问“给我一个 java.lang.Object 的真实例子”:)
标签: scala functional-programming composition functor scalaz