我有一个Seq[R]
,我想把它分成一个Tuple2[Seq[E], Seq[S]]
,在我编码这个的时候,我想到了一个事实,我可以Bifunctor
为一个 seqs 的元组使用一个自定义,并且作为练习试图编码这个:
import scalaz.Bifunctor
type MyType[E, S] = (Seq[E], Seq[S])
case class MyVali[E, S](tp: (Seq[E], Seq[S]))(implicit bifunctor: Bifunctor[MyType]) {
def bimap[C, D](f: (E) => C, g: (S) => D): (Seq[C], Seq[D]) =
bifunctor.bimap(tp)(f, g)
def leftMap[C](f: (E) => C): (Seq[C], Seq[S]) =
bifunctor.leftMap(tp)(f)
def rightMap[D](g: (S) => D): (Seq[E], Seq[D]) =
bifunctor.rightMap(tp)(g)
}
val myValBifunctorInstance = new Bifunctor[MyType] {
override def bimap[A, B, C, D](fab: (Seq[A], Seq[B]))(f: (A) => C, g: (B) => D): (Seq[C], Seq[D]) =
(fab._1.map(f), fab._2.map(g))
}
MyVali((Seq.empty[String], Seq.empty[Int]))(myValBifunctorInstance).bimap(a => a, b => b)
这工作正常,但由于某种原因对我来说晦涩难懂,我不得不声明一个参数化类型别名来使所有这些编译,也就是说type MyType[E, S] = (Seq[E], Seq[S])
,我几乎不明白为什么这行得通,而这行不通:
def myValBimap[E, S] = new Bifunctor[Tuple2[Seq[E], Seq[S]]] {
override def bimap[A, B, C, D](fab: (A, B))(f: (A) => C, g: (B) => D): (C, D) = ???
}
[错误] ... (Seq[E], Seq[S]) 没有类型参数,预期:两个
[错误] def myValBimap[E, S] = new Bifunctor[Tuple2[Seq[E], Seq[S]]] {
当定义了这样的类型别名时,编译器是否创建了 2-type 暂停(可能像嵌套的 lambda 类型?)?