【发布时间】:2013-05-05 19:39:07
【问题描述】:
有一种明确的方法可以将二进制递归转换为尾递归,用于在函数下关闭的集合,即斐波那契数列的加法整数:
(使用 Haskell)
fib :: Int -> Int
fib n = fib' 0 1 n
fib' :: Int -> Int -> Int
fib' x y n
| n < 1 = y
| otherwise = fib' y (x + y) (n - 1)
之所以可行,是因为我们有我们想要的值 y 和我们的操作 x + y,其中 x + y 返回一个整数,就像 y 一样。
但是,如果我想使用一个在函数下没有闭合的集合怎么办?我想采用一个函数,将一个列表拆分为两个列表,然后对这两个列表执行相同操作(即,像递归地创建二叉树),当另一个函数神奇地说何时停止查看结果拆分时,我会停止:
[1, 2, 3, 4, 5] -> [[1, 3, 4], [2, 5]] -> [[1, 3], [4], [2], [5]]
也就是说,
splitList :: [Int] -> [[Int]]
splitList intList
| length intList < 2 = [intList]
| magicFunction x y > 0 = splitList x ++ splitList y
| otherwise = [intList]
where
x = some sublist of intList
y = the other sublist of intList
现在,如何将此二进制递归转换为尾递归?先前的方法不会显式工作,因为(Int + Int -> Int 与输入相同)但(Split [Int] -/> [[Int]] 与输入不同)。因此,累加器需要更改(我假设)。
【问题讨论】:
标签: haskell functional-programming binary-tree tail-recursion