0
意図したとおり、この1でもassert(!balance("())(".toList))
で、動作します。ロジックを動かして機能が変化するのはなぜですか?
def balance(chars: List[Char]): Boolean = {
def balanceR(chars: List[Char], depth: Int): Boolean = {
if (chars.isEmpty)
depth == 0
else if (chars.head == '(') balanceR(chars.tail, depth + 1)
else if (chars.head == ')') {
if (depth == 0) false else balanceR(chars.tail, depth - 1)
}
else balanceR(chars.tail, depth)
}
balanceR(chars, 0)
}
はしかし、「深さが負になった場合はfalseを返す」ためのロジックの配置を変更すると、失敗する同じアサーションが発生します。
def balance(chars: List[Char]): Boolean = {
def balanceR(chars: List[Char], depth: Int): Boolean = {
if (depth < 0)
false
if (chars.isEmpty)
depth == 0
else if (chars.head == '(') balanceR(chars.tail, depth + 1)
else if (chars.head == ')') balanceR(chars.tail, depth - 1)
else balanceR(chars.tail, depth)
}
balanceR(chars, 0)
}
chars.head
が")"
のときの再帰呼び出しがbalanceR("(", -1)
であるときに、2番目の関数が"())("
に対してfalseを返さないのはなぜですか?これはScalaのコーセラからのものであり、そのトピックにここにMODのコメントを見ること
注:あなたが効果的に何もしないスタンドアロン式を作成しましたScala way to program bunch of if's
これは、スカラがどのように返ってくるのか誤解しているようです。私はif文の後に1つの文を見たときに、その文を返すと考えました。 私は言う必要はありません: 'return balanceR(chars.tail、depth +1)' –
提案は問題を解決します。同様に、私は暗黙のうちに 'if'の後に' return false'と言うこともできますし、提案したように2番目の枝を 'else if'に変更することもできます。 –
@TaylorKline Scalaは、メソッド内の最後のステートメントの結果を返します。メソッドの最後にない文(最初のifのような)は、単に破棄されます。あなたが言うように、ここではリターンを使うことができますが、通常はリターンを使わない方が良い方法です。 – puhlen