将循环转换为递归解

时间:2020-02-29 21:28:03

标签: scala recursion functional-programming tail-recursion pythagorean

我已经在Scala中使用嵌套循环编写了方法pythagoreanTriplets。作为scala中的新手,我正在努力使用递归来做同样的事情,并为返回列表(元组列表)使用惰性评估。任何帮助将不胜感激。

P.S:以下方法运行良好。

// This method returns the list of all pythagorean triples whose components are
// at most a given limit. Formula a^2 + b^2 = c^2

def pythagoreanTriplets(limit: Int): List[(Int, Int, Int)] = {
    // triplet: a^2 + b^2 = c^2
    var (a,b,c,m) = (0,0,0,2)
    var triplets:List[(Int, Int, Int)] = List()
    while (c < limit) {
      breakable {
        for (n <- 1 until m) {
          a = m * m - n * n
          b = 2 * m * n
          c = m * m + n * n
          if (c > limit)
            break
          triplets = triplets :+ (a, b, c)
        }
        m += 1
      }
    }// end of while
    triplets
  }

1 个答案:

答案 0 :(得分:4)

我看不到递归将在哪些方面提供明显优势。

def pythagoreanTriplets(limit: Int): List[(Int, Int, Int)] = 
  for {
    m <- (2 to limit/2).toList
    n <- 1 until m
    c =  m*m + n*n if c <= limit
  } yield (m*m - n*n, 2*m*n, c)