4

我有一个叫做 a 的东西Generator

trait Generator[A, B] {
  def generate(in: Seq[A]): Seq[B]
}

我可以Bind为这个生成器提供一个实例:

object Generator {
  implicit def generatorBind[T]: Bind[({type l[B] = Generator[T, B]})#l] = new Bind[({type l[B] = Generator[T, B]})#l] {

    def map[A, B](generator: Generator[T, A])(f: A => B): Generator[T, B] = new Generator[T, B] {
      def generate(in: Seq[T]): Seq[B] = generator.generate(in).map(f)
    }

    def bind[A, B](generator: Generator[T, A])(f: A =>Generator[T, B]): Generator[T, B] = new Generator[T, B] {
      def generate(in: Seq[T]): Seq[B] = generator.generate(in).flatMap(v => f(v).generate(in))
    }
  }
}

不幸的是,如果我尝试将生成器用作应用实例,则类型推断将完全丢失:

val g1 = new Generator[Int, Int] { def generate(seq: Seq[Int]) = seq.map(_ + 1) }
val g2 = new Generator[Int, Int] { def generate(seq: Seq[Int]) = seq.map(_ + 10) }

// doesn't compile
// can make it compile with ugly type annotations
val g3 = ^(g1, g2)(_ / _)

我现在唯一的解决方法是向Generator对象添加一个专门的方法:

def ^[T, A, B, C](g1: Generator[T, A], g2: Generator[T, B])(f: (A, B) => C) = 
  generatorBind[T].apply2(g1, g2)(f)

然后编译:

val g4 = Generator.^(g1, g2)(_ / _)

有解决此问题的方法吗?我想这是因为使用State[S, A]as a会Monad带来同样的问题(但在 Scalaz 中似乎对 有特殊处理State)。

4

2 回答 2

2

如果显式注释和类型,您可以使用ApplicativeBuilder,或者更改为g1g2abstract class Generator

// java.lang.Object with Generator[Int, Int] !!!
val badInference = new Generator[Int, Int] { def generate(seq: Seq[Int]) = seq.map(_ + 1) }

val g1: Generator[Int, Int] = new Generator[Int, Int] { def generate(seq: Seq[Int]) = seq.map(_ + 1) }
val g2: Generator[Int, Int] = new Generator[Int, Int] { def generate(seq: Seq[Int]) = seq.map(_ + 10) }
val g3 = (g1 |@| g2)(_ / _)
于 2013-09-20T03:30:57.740 回答
0

我认为隐式宏的fundep实现(又名功能依赖)是为了帮助这一点。

trait Iso[T, U] {
  def to(t: T) : U
  def from(u: U) : T
}
case class Foo(i: Int, s: String, b: Boolean)
def conv[C](c: C)(implicit iso: Iso[C, L]): L = iso.from(c)
val tp  = conv(Foo(23, "foo", true))

它需要宏观天堂。

于 2013-09-20T01:26:52.443 回答