Mar*_* T. 3 functional-programming scala
假设我的代码中定义了许多布尔谓词:
def pred1[A](x: A): Boolean = { ... }
def pred2[A](x: A): Boolean = { ... }
def pred3[A](x: A): Boolean = { ... }
Run Code Online (Sandbox Code Playgroud)
现在,我希望能够创建一个函数,例如,逻辑OR的pred1和pred3.
所以,像:
def pred1Or3[A](x: A) = or(pred1, pred2)
Run Code Online (Sandbox Code Playgroud)
更好的是,能够推广以便我可以提供自己的组合功能会很好.所以,如果相反,我想要有逻辑AND,我会打电话:
def pred1And3[A](x: A) = combine({_ && _}, pred1, pred2)
Run Code Online (Sandbox Code Playgroud)
我可以用这种方式达到同样的基本效果:
def pred1And3[A](x: A) = Seq(pred1, pred2) map { _(x) } reduce { _ && _ }
Run Code Online (Sandbox Code Playgroud)
但这看起来有点冗长,并且意味着什么.在Scala中有更简单的方法吗?
这是一个简单的解决方案,允许同时传递可变数量的项目.我已经给出了or案例和更通用的combine案例:
def or[A](ps: (A => Boolean)*) =
(a: A) => ps.exists(_(a))
def combine[A](ps: (A => Boolean)*)(op: (Boolean, Boolean) => Boolean) =
(a: A) => ps.map(_(a)).reduce(op)
Run Code Online (Sandbox Code Playgroud)
以下是一些示例用法:
// "or" two functions
val pred1or3 = or(pred1, pred3)
pred1or3("the")
// "or" three functions
val pred12or3 = or(pred1, pred2, pred3)
pred12or3("the")
// apply a dijoined rule directly
or(pred1, pred2, pred3)("the")
// combine two functions with "and"
val pred12and3 = combine(pred1, pred3)(_ && _)
pred12and3("the")
// apply a conjoined rule directly
combine(pred1, pred2, pred3)(_ && _)("the")
// stack functions as desired (this is "(pred1 || pred3) && (pred1 || pred2)")
combine(or(pred1, pred3), or(pred1, pred2))(_ && _)("a")
Run Code Online (Sandbox Code Playgroud)