这是来自 Haskell 实现的相关代码,该例程计算列表中的反转
mergeAndCount :: Ord a => [a] -> [a] -> (Int,[a])
mergeAndCount l@(x:xs) r@(y:ys) | x < y = let (inv, s) = mergeAndCount xs r in (inv, x:s)
| otherwise = let (inv, s) = mergeAndCount l ys in (inv + rest, y:s)
where rest = length l
mergeAndCount l [] = (0, l)
mergeAndCount [] r = (0, r)
我曾尝试在 Scala 中编写类似的例程,但它会因堆栈溢出而崩溃(不过,惰性排序有效)。这是非工作版本:
def mergeAndCount(l: Stream[Int], r: Stream[Int]) : (Long, Stream[Int]) = {
(l, r) match {
case (x#::xs, Empty) => (0, l)
case (Empty, y#::ys) => (0, r)
case (x#::xs, y#::ys) => if(x < y) {
lazy val (i, s) = mergeAndCount(xs, r)
(i, x#::s)
} else {
lazy val (i, s) = mergeAndCount(l, ys)
(i + l.length, y#::s)
}
}
}
关于如何使 Scala 版本表现得像 Haskell 的任何想法?