scala递归函数抛出Stackoverflow异常

时间:2018-01-11 13:55:52

标签: scala haskell recursion

def bubblesort(xs: List[Int]): List[Int] = xs match {
    case List()  => List()
    case List(x) => List(x)
    case x :: y :: rest =>
      {
        def bubbled(x1: Int, y1: Int) = {
          val (first, second) = if (x1 > y1) (y1, x1) else (x1, y1)
          first :: bubblesort(second :: rest)
        }
        bubblesort(bubbled(x, y).init) ++ List(bubbled(x, y)).last
      }
  }

1。上面的代码Stackoverflow异常,实际上我从scala中的下面的haskell代码中翻译了相同的代码。

bubblesort2 :: (Ord a, Show a) => [a] -> [a]
bubblesort2 [] = []
bubblesort2 [x] = [x]
bubblesort2 (x:y:rest) =
    bubblesort2 (init bubbled) ++ [last bubbled]
    where
        (first,second) = if x > y then (y,x) else (x,y)
        bubbled = first : bubblesort2(second:rest)

scala代码有什么问题?

1 个答案:

答案 0 :(得分:2)

你在scala代码中犯了错误:

bubblesort2 (init bubbled) ++ [last bubbled]

应翻译为

bubblesort(bubbled(x, y).init) :+ bubbled(x, y).last

在您的代码中bubblesort(bubbled(x, y).init) ++ List(bubbled(x, y)).last 引导您进行无限递归。