Scala 递归举例

1.求和

def sum(num: Int): Int = if (num == 1) 1 else num + sum(num - 1)

2.求最大值

def max(list: List[Int]): Int = {
  if (list.size == 1) {
    list.head
  } else {
    if (list.head > max(list.tail)) list.head else max(list.tail)
  }
}

3.反转字符串

def reverse(str: String): String = {
  if (str.length == 1) str
  else reverse(str.tail) + str.head
}

4.求阶乘

def factorial(num: Int): BigInt = {
  if (num == 1) num
  else num * factorial(num - 1)
}

5.求斐波那契数列。

def fibonacci(num: Int): Int = {
  if (num == 1 || num == 2) 1
  else fibonacci(num - 1) + fibonacci(num - 2)
}

  在例2和例5中,由于存在重复递归,效率很低。

原文地址:https://www.cnblogs.com/noyouth/p/12822334.html