【发布时间】:2015-08-28 16:07:35
【问题描述】:
假设我有几个函数Int => Int 由andThen 组成:
val f1: Int => Int = _ + 1
val f2: Int => Int = _ + 2
val f3: Int => Int = _ + 3
val f = f1 andThen f2 andThen f3
现在我还需要返回中间结果。所以我可以将所有这些函数转换为Int => (List[Int], Int),其中列表包含参数。
我大概可以使用scalaz中的Writer[List[Int], Int]来表示(List[Int], Int)这对:
val fw1: Int => Writer[List[Int], Int] = x => f1(x).set(List(x))
val fw2: Int => Writer[List[Int], Int] = x => f2(x).set(List(x))
val fw3: Int => Writer[List[Int], Int] = x => f3(x).set(List(x))
为了编写fw1、fw2 和fw3,我可能需要用Kleisli 包装它们。但是 Kleisli(fw1) 无法编译,因为 Writer[List[Int], Int] 不是 monad。
我想我可能需要一个 monad transformer 来使 Writer[List[Int], Int] 成为一个单子,但我不知道该怎么做。所以,我的问题是:如何使 Kleisli(fw1) 用 monad 转换器编译?
【问题讨论】:
标签: scala scalaz monad-transformers writer-monad