Scala 编写嵌套if-else语句的更好方法

Scala 编写嵌套if-else语句的更好方法,scala,if-statement,nested,Scala,If Statement,Nested,什么是编写以下逻辑的最佳Scala方式 def collatzAlgorithm(target: Int): Int = { if (target % 2 == 0) { val new_target = target / 2 if (new_target == 1) { new_target } else { if (new_target % 2 != 0) { new_target * 3 + 1

什么是编写以下逻辑的最佳Scala方式

def collatzAlgorithm(target: Int): Int = {
    if (target % 2 == 0) {
      val new_target = target / 2
      if (new_target == 1) {
        new_target
      } else {
        if (new_target % 2 != 0) {
          new_target * 3 + 1
        } else {
          new_target
        }
      }
    } else {
      target
    }
  }

谢谢

与其说是scala方式,不如说是需要简化和扁平化嵌套。我会将其重构为:

val newTarget = target / 2
if (newTarget % 2 == 0) {
  newTarget
} else if (newTarget != 1) {
  newTarget * 3 + 1
} else {
  1
}
然而,很难说它是否真的做到了你认为它能做到的,因为你正在令人困惑地试图向前迈进一步。我会写一个collatz序列,比如:

Iterator.iterate(n){n => if (n % 2 == 0) n / 2 else 3 * n + 1}.takeWhile{_ != 1}

这以2结尾,但如果确实需要以1结尾,则可以添加++迭代器1。

您的代码会产生错误的结果:

(1 to 10).map (collatzAlgorithm)
// Vector(1, 1, 3, 2, 5, 10, 7, 4, 9, 16)
所有的奇数值都没有改变。以下是一个可行的解决方案:

def collatzAlgorithm (target: Int): Int = {
    if (target == 1) 1
    else target % 2 match {
        case 0 => target / 2 
        case 1 => target * 3 + 1
    }
}   

(1 to 10).map (collatzAlgorithm)
// Vector(1, 1, 10, 2, 16, 3, 22, 4, 28, 5)

您可以考虑递归算法,它立即调用下一步:

def collatz (target: Int): Int = {
    if (target == 1) 1
    else target % 2 match {
        case 0 => collatz (target / 2)
        case 1 => collatz (target * 3 + 1)
    }
} 
对于较小的值,它可以正常工作:

(1 to 10).map (collatz)
// Vector(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

然而,对于更大和更多的输入,同样的序列会被一次又一次地计算,因此解决方案应该与某种形式的记忆一起工作,以避免这种低效

这看起来不像collatz算法,除非这是正在迭代的函数。为什么要检查两次偶数结果?对于1到10.map collatzAlgo,我得到向量1,1,3,2,5,10,7,4,9,16,这表明所有奇数返回不变。因此,在优化算法之前,您应该先修复它。缓慢或冗长但正确的代码比简短或快速的代码要好。