Writing type class instances for nested classes in Scala

痞子三分冷 提交于 2019-11-29 04:08:16

I usually add implicit extension to Parser in mixins for Parsers

trait BindForParser extends Parsers {
  implicit def ParserBind = new Bind[Parser] {
    def bind[A,B](p: Parser[A], f: A => Parser[B]) = p flatMap f
  }
}

Then you just have to mix that in your grammar (Parsers), and as Parser instances are usually manipulated only inside Parsers, there are not much chances the mixin would be needed afterwards, when the grammar is done and you can no longer mix something in. In your example, you just do

object parser extends Parsers with BindForParser

On the more general question, whether it is possible to do it "from the outside", the most direct way would probably be something like

implicit def ParserBind(grammar: Parsers) = new Bind[grammar.Parser] {
  def bind[A,B](p: grammar.Parser[A], f: A => grammar.Parser[B]) = p flatMap f
}

But this is not allowed, a method parameter (here grammar) is not considered a stable identifier and so grammar.Parser is not allowed as a type. It is however possible with option -Xexperimental. But even then, I don't see how the implicit would kick in when needed. What we want is an implicit Bind[grammar.Parser], and with the grammar parameter this is not what we have.

So my answer would be it cannot be done, but I would not be that surprised if someone could come up with something.

Dealing with the path dependent types is pretty tricky. Here's one way:

https://github.com/retronym/scalaz7-experimental/commit/8bf1d2a090cf56d33e11c554e974ea3c82b7b37f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!