给定一个函数,在记录 s 时f: A => E \/ B
收集B
某些 s 列表结果的惯用方法是什么?A
E
我想出了以下内容(部分是在回答这个 SO question时):
import scalaz._, Scalaz._
type Logger[+A] = Writer[List[String], A]
def logged[A, E, B, F[_]](f: A => E \/ B)(implicit FM: Monoid[F[E]], FP: Pointed[F]): (A => Writer[F[E], Option[B]]) =
(a: A) => f(a).fold(e => Writer(FP.point(e), None), b => Writer(FM.zero, Some(b)))
def listLogged[A, E, B](f: A => E \/ B) = logged[A, E, B, List](f)
type W[+A] = Writer[List[String], A]
def keepOdd(n: Int): String \/ Int =
if (n % 2 == 1) \/.right(n) else \/.left(n + " was even")
scala> val x = List(5, 6).traverse[W, Option[Int]](listLogged(keepOdd))
x: W[List[Option[Int]]] = scalaz.WriterTFunctions$$anon$26@503d0400
scala> x.run
res11: (List[String], List[Option[Int]]) = (List(6 was even),List(Some(5), None))
scala> val (logs, results) = x.map(_.flatten).run
logs: List[String] = List(6 was even)
results: List[Int] = List(5)
有没有更短/更好/限制更少/更通用的方法?