代码之家  ›  专栏  ›  技术社区  ›  Teja Kantamneni

斯卡拉有警卫吗?

  •  43
  • Teja Kantamneni  · 技术社区  · 16 年前

    functional programming 语言如( Haskell Erlang )我对它有些熟悉。斯卡拉有吗 guard 序列可用吗?

    我在Scala中进行了模式匹配,但是有没有任何概念可以与具有 otherwise 所有这些呢?

    4 回复  |  直到 11 年前
        1
  •  56
  •   Nathan Shively-Sanders    16 年前

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

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

    (报纸上没有提到这一点 Pattern Matching


    在哈斯克尔, otherwise 实际上只是一个绑定到 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
    
        2
  •  19
  •   sepp2k    16 年前

    是的,有图案保护装置。它们是这样使用的:

    def boundedInt(min:Int, max: Int): Int => Int = {
      case n if n>max => max
      case n if n<min => min
      case n => n
    }
    

    请注意 otherwise -子句,您只需在没有保护的情况下指定模式。

        3
  •  9
  •   Peter Mortensen Pieter Jan Bonestroo    13 年前

    简单的答案是否定的。它并不完全符合您的要求(与Haskell语法完全匹配)。您可以将Scala的“匹配”语句用于一个守卫,并提供一个通配符,如:

    num match {
        case 0 => "Zero"
        case n if n > -1 =>"Positive number"
        case _ => "Negative number"
    }
    
        4
  •  4
  •   cevaris    12 年前

    def func(x: Int, y: Int): String = (x, y) match {
      case (_, 0) | (0, _)  => "Zero"
      case (x, _) if x > -1 => "Positive number"
      case (_, y) if y <  0 => "Negative number"
      case (_, _) => "Could not classify"
    }
    
    println(func(10,-1))
    println(func(-10,1))
    println(func(-10,0))
    
    推荐文章