简体   繁体   English

使用隐式约束抽象类型成员的特征的限制方法?

[英]Restrict method of a trait with constraint on abstract type member using implicits?

I am in the situation below: 我处于以下情况:

import scalaz.Leibniz._

trait Exp[T, C] {

   def &&(that: Exp[T, C])(implicit evT: T === Boolean) = LogicalAnd(this, that)
   def &&(that: Exp[T, C])(implicit evT: T === Int) = BitwiseAnd(this, that)

}

case class LogicalAnd[C](e1: Exp[Boolean, C], e2: Exp[Boolean, C]) extends Exp[Boolean, C] 
case class LogicalOr[C](e1: Exp[Boolean, C], e2: Exp[Boolean, C]) extends Exp[Boolean, C] 
...
case class BitwiseAnd[C](e1: Exp[Int, C], e2: Exp[Int, C]) extends Exp[Int, C]
case class BitwiseOr[C](e1: Exp[Int, C], e2: Exp[Int, C]) extends Exp[Int, C]
...

The trait Exp[T,C] is the base trait for and AST for a DSL, I would like to overload built-in scala operators in this trait to allow for infix notation over this dsl, however I would like to constrain some of these methods with a bound on the type T at the trait level so that the same operation here '&&' has a different semantics depending on the type T. 特征Exp [T,C]是DSL的基本特征和AST,我想在此特征中重载内置scala运算符,以允许在此dsl上使用中缀表示法,但是我想限制其中一些在特征级别的类型T上具有约束的方法,因此此处的“ &&”操作根据类型T具有不同的语义。

It seems that the leibniz subsitution does not/cannot work here (maybe because it is only defined for functors F[_] with a single argument): 似乎leibniz替换在这里不能/不能工作(也许是因为它仅针对具有单个参数的函子F [_]定义):

[error] /home/remi/Projects/DSL/src/main/scala/Exp.scala:80: type mismatch;
[error]  found   : exp.Exp[T,C]
[error]  required: exp.Exp[Boolean,?]
[error]   = LogicalAnd(this, that)
[error]         ^

Does this approach to constraining the trait's T parameter make sense at all ? 这种约束性状的T参数的方法是否完全有意义? Is there a way to make leibniz work in this case by "hiding" the second parameter C with something like : 有没有一种方法可以使leibniz在这种情况下起作用,方法是将第二个参数C“隐藏”起来,例如:

type ExpF[T] = Exp[T, _]

if that even makes sense? 那是否有意义? Thanks, 谢谢,

Exactly that; 就是这样 define such a type and then use Leibniz.lift to, well, lift your Leibniz : 定义这样的类型,然后使用Leibniz.lift来提升您的Leibniz

def &&(that: Exp[T, C])(implicit evT: T === Boolean) = {
  type ExpF[A] = Exp[A, C]
  val ev2: (Exp[T, C] === Exp[Boolean, C]) =
    Leibniz.lift[⊥, ⊥, ⊤, ⊤, ExpF, T, Boolean](evT)
  LogicalAnd(this, that)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM