我試圖改善traverse_
功能在下面的代碼的類型推斷:是否可以改進Scala中部分應用類型的類型推斷?
import scala.language.higherKinds
trait Applicative[AF[_]] {
def ap[A, B](a: AF[A])(f: AF[A => B]): AF[B]
def pure[A](a: A): AF[A]
def fmap[A, B](a: AF[A])(f: A => B): AF[B]
}
def traverse_[AP[_]: Applicative, A](xs: Iterable[A])(f: A => AP[Unit]): AP[Unit] = {
val ap = implicitly[Applicative[AP]]
(xs :\ ap.pure(())) { (x, acc) =>
val apFunc = ap.fmap(f(x))(a => identity[Unit] _)
ap.ap(acc)(apFunc)
}
}
implicit def optionAp = new Applicative[Option] {
def ap[A, B](a: Option[A])(f: Option[A => B]): Option[B] = f flatMap (a map _)
def pure[A](a: A) = Some(a)
def fmap[A, B](a: Option[A])(f: A => B) = a map f
}
implicit def eitherAp[L] = new Applicative[({type l[x]=Either[L, x]})#l] {
def ap[A, B](a: Either[L, A])(f: Either[L, A => B]): Either[L, B] = f.right flatMap (a.right map _)
def pure[A](a: A) = Right(a)
def fmap[A, B](a: Either[L, A])(f: A => B) = a.right map f
}
// silly, but compiles
val x = traverse_(1 to 10) {
case 5 => None
case _ => Some(())
}
println(x)
// also silly, but does not compile
val y = traverse_(1 to 10) {
case 5 => Left("x")
case _ => Right(())
}
println(y)
上面運行給出:
/Users/lodea/tmp/traverse.scala:49: error: no type parameters for method traverse_: (f: Int => AP[Unit])(implicit evidence$1: this.Applicative[AP])AP[Unit] exist so that it can be applied to arguments (Int => Product with Serializable with scala.util.Either[String,Unit])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : Int => Product with Serializable with scala.util.Either[String,Unit]
required: Int => ?AP
val y = traverse_(1 to 10) {
^
/Users/lodea/tmp/traverse.scala:49: error: type mismatch;
found : Int => Product with Serializable with scala.util.Either[String,Unit]
required: Int => AP[Unit]
val y = traverse_(1 to 10) {
^
two errors found
爲了得到它來編譯,我必須指定類型參數的traverse_
:
val y = traverse_[({type l[x]=Either[String, x]})#l, Int](1 to 10) {
case 5 => Left("x")
case _ => Right(())
}
有沒有一種方法可以讓我重組traverse_
,或代碼的任何其他部分,使類型推斷工作?當類型開始變得越來越複雜時,這會變得很快。
邁爾斯薩賓發現了一個這樣做的方法,用於在斯卡拉斯實施'traverseU'。這聽起來就像你正在做的事情。 – 2013-03-08 16:11:37