私は以下の場合をscalaに持っています:
myList は List[String] の一部です
if (myList.isEmpty) return x > 5
if x < 0 return false
if (myList.head == "+") return foo()
if (myList.head == "-") return bar()
パターンマッチングでそれを行うことは可能ですか?
私は以下の場合をscalaに持っています:
myList は List[String] の一部です
if (myList.isEmpty) return x > 5
if x < 0 return false
if (myList.head == "+") return foo()
if (myList.head == "-") return bar()
パターンマッチングでそれを行うことは可能ですか?
少し厄介ですが、うまくいくはずです:
myList match {
case Nil => x > 5
case _ if x < 0 => false
case "+" :: _ => foo()
case "-" :: _ => bar()
}
一致が完全ではないことに注意してください。
私にとって、これはよりきれいです:
if(x > 0) {
myList.headOption match {
case Some("+") => foo()
case Some("-") => bar()
case None => x > 5
} else false
しかし、これが論理的な流れに直面していないかどうかはわかりません(たとえば、リストが空の場合の早期終了-コンテキストで何かが壊れているかどうか)、そうであれば、遠慮なくそう言うか、反対票を投じてください。
つまり、空のリストだけでなく、リスト内のアイテムでも照合できます。一致せずに条件だけが必要な場合は、次を使用しますcase _ if ...
。
def sampleFunction: Boolean =
lst match {
case Nil => x > 5
case _ if (x < 0) => false
case "+" :: _ => true
case "-" :: _ => false
case _ => true // return something if nothing matches
}