Scala-前缀一元运算符 [英] Scala - Prefix Unary Operators

查看:196
本文介绍了Scala-前缀一元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近又给了Scala一次机会,并从我始终以功能或伪功能语言实施的项目开始:命题逻辑(以及后来的谓词逻辑)的自动推理机.

I've recently given Scala a second chance, and started with the project I always implement (in functional or pseudo-functional languages): an automated reasoner for propositional logic (and later predicate logic).

现在,我试图在语言本身中尽可能地获得命题逻辑的表示法,并且到目前为止,我进行了隐式转换(字符串-> Atom):

Now, I've tried to get the notation of propositional logic in the language itself as pretty as possible, and I've gotten this far - with an implicit conversion (String -> Atom):

("A" and "B") implies "C"

函数"and"和"implies"(以及"or"和"equivalent")是调用相关案例类构造函数的简单方法.但是,在实现"not"时,我陷入了以下两种表示方式之一:

The functions "and" and "implies" (and "or" and "equivalent") are simple methods that call the relevant case class constructor. However, when implementing "not", I get stuck with either of the two following notations:

("A" and "B").not
Not("A" and "B")

有没有一种方法可以欺骗Scala接受所需的内容:

Is there a way to trick Scala into accepting the desired:

not("A" and "B")

最好不要将"Not"类重命名为"not",因为将来我可能会称其为¬"或其他名称.

Preferrably without renaming the class "Not" to "not", because I might like to call it "¬" or something else, in th future.

推荐答案

自2014年2月起,我认为在表达式上定义前缀'ish not操作的最简洁方法是,同时避免了各种额外的填充/包装,将直接在包范围中声明该函数,以及所有其他函数,类,类型等:这是通过定义包对象来完成的(Scala不允许您仅将函数放在.scala文件(我想学习为什么-只是遵循Java的脚步吗?).

As of Feb 2014, I think the cleanest way to define a prefix'ish not operation on expressions, while avoiding all sorts of extra cruft/wrapping, would be to declare the function directly in the package scope, together with all your other functions, classes, types etc: This is done by defining a package object (Scala doesn't allow you to just put functions at the root level of the .scala file (I'd love to learn why—is it just to follow Java's footsteps?)).

package org.my.logiclib

implicit class Atom(s: String) { ... }
class MyType1
class MyType2

object `package` {
  def not(expr: Expr) = ...
}

这样,执行import org.my.logiclib._将会导入所有内容,包括not().

this way, doing import org.my.logiclib._ will import everything, including not().

以上与

package org.my

package logiclib {
  implicit class Atom ...
  ...

  def not(expr: Expr) = ...
}

这篇关于Scala-前缀一元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆