循环到递归解的转换

问题描述 投票:1回答:1

我已经使用嵌套循环在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
  }
scala recursion functional-programming tail-recursion pythagorean
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.