scala - Scala 有守卫吗?

标签 scala functional-programming

我几天前开始学习scala,在学习它的时候,我正在将它与其他的进行比较functional programming像( HaskellErlang )这样的语言我有一些熟悉。 Scala 有 guard序列可用吗?

我在 Scala 中进行了模式匹配,但是有没有与 otherwise 和所有的守卫等效的概念?

最佳答案

是的,它使用关键字if。来自 Case Classes Scala 之旅的部分,靠近底部:

def isIdentityFun(term: Term): Boolean = term match {
  case Fun(x, Var(y)) if x == y => true
  case _ => false
}

(Pattern Matching 页面上没有提到这一点,可能是因为游览是如此快速的概述。)

<小时/>

在 Haskell 中,otherwise 实际上只是一个绑定(bind)到 True 的变量。所以它并没有给模式匹配的概念增加任何力量。您只需在没有防护的情况下重复初始模式即可获得它:

// if this is your guarded match
  case Fun(x, Var(y)) if x == y => true
// and this is your 'otherwise' match
  case Fun(x, Var(y)) if true => false
// you could just write this:
  case Fun(x, Var(y)) => false

关于scala - Scala 有守卫吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2266915/

相关文章:

scala - Spark 和 HBase 快照

performance - coursera progfun1 : scala union performance

scala - 如果 M 是一个 monad,如何正确地将 List[M[List[A]]] 组合到 M[List[A]] 中?

functional-programming - Coq:证明n和(S n)的乘积是偶数

c++ - "filter"C++ 中的高阶函数

javascript - 这个带有可变引用参数的 JavaScript 函数是纯函数吗?

java - 如何使用 maven jvmArg 解决 "GC overhead limit exceeded"?

scala - fp 风格的做法是什么 "naive hashmap"

Java 重用接口(interface)方法

scala - 如何在 Scala 中将 Map[Symbol, List[A]] 转换为 List[Map[Symbol,A]] ?