将对象定义为Scala中其他两个对象的操作
发布时间:2020-12-16 18:12:00 所属栏目:安全 来源:网络整理
导读:我正在 Scala中为大学的实验室实施符号分析. 为此,我需要对Pos,Neg,Zero等抽象值进行算术运算. NonPos,NonNeg,…所以我必须声明方法,–,*,/ etc … on 那些抽象的价值.我实际上不需要定义所有内容 成对,但可以定义Pos,Neg和Zero上的“核心”操作, 然后使用上
我正在
Scala中为大学的实验室实施符号分析.
为此,我需要对Pos,Neg,Zero等抽象值进行算术运算. NonPos,NonNeg,…所以我必须声明方法,–,*,/ etc … on 那些抽象的价值.我实际上不需要定义所有内容 成对,但可以定义Pos,Neg和Zero上的“核心”操作, 然后使用上限来定义,例如: NonPos + Pos = leastUpperBound(Zero + Pos,Neg + Pos) 例如,leastUpperBound(Zero,Neg)= NonPos 在Scala中,我使用case对象来表示值,并且有一个 case object NonNeg extends Sign { def +(other: Sign) = leastUpperBound(Zero + other,Pos + other) def -(other: Sign) = ... def * = ... ... } 我必须做同样的事情: case object NonPos extends Sign { def +(other: Sign) = leastUpperBound(Zero + other,Neg + other) ... } 然后再次: case object NonZero extends Sign { def +(other: Sign) = leastUpperBound(Neg + other,Neg + other) ... } 我想知道是否有可能拥有某种“类型工厂”以便我能做到 case object NonNeg extends UpperBoundSign[Pos,Zero] 我的直觉是,Pos和Zero是对象是不可能的, 有没有人有任何想法删除这种重复? 我希望问题很清楚, 编辑:感谢@cmbaxter的回答以及我的一些重构,我提出了一个我喜欢的解决方案.如果有人有兴趣看到它,可以在那里找到:https://gist.github.com/Ricordel/5553405. 解决方法
我想你可能会混淆类型标识符和类的实例.我相信,为了获得你想要的功能,你需要将UpperBoundSign定义为一个带有两个构造函数args的抽象类,而不是具有两个类型标识符槽的泛型类型.这是一个过于简化的解决方案选项,可以满足您的需求.如果这完全不是你想要的,我道歉:
trait Sign{ def +(other: Sign):Sign } abstract class UpperBoundSign(pos:Sign,neg:Sign) extends Sign{ def leastUpperBound(pos:Sign,neg:Sign):Sign def +(other: Sign) = leastUpperBound(pos + other,neg + other) } case object Pos extends Sign{ def +(other:Sign) = ... } case object Neg extends Sign{ def +(other:Sign) = ... } case object NonNeg extends UpperBoundSign(Pos,Neg){ def leastUpperBound(pos:Sign,neg:Sign) = ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |