我的任务是创建一个递归函数,它接受一个列表并给出列表的反向。
我已经能够创建一个名为rev1
的函数来执行此操作:
rev1 :: [a] -> [a]
rev1 [] = []
rev1 (x:xs) = reverse xs ++ [x]
但是我被要求创建另一个函数'rev2',它应该使用一个额外的参数作为累加器。
请有人帮我撰写rev2
函数。
提前致谢, 萨姆
答案 0 :(得分:3)
首先,您的im = imread( 'ngc6543a.jpg' ); % matlab example image
x = randn( size (im) ); % create gaussian distributed values
t = im + x; % add them together, this throws the error
应该是这样的:
rev1
rev1 :: [a] -> [a]
rev1 [] = []
rev1 (x:xs) = rev1 xs ++ [x]
的要点是通过在累加器参数中传递中间结果来实现尾递归:
rev2
然而,这显然存在向rev2 :: [a] -> [a] -> [a]
-- if applied to an empty list, just return the result
-- so far, i.e. whatever is inside the accumulator:
rev2 acc [] = acc
-- otherwise, take the head of the list and append it to
-- the accumulator, and carry on with the rest of the list
rev2 acc (x:xs) = rev2 (x:acc) xs
的用户公开acc
参数的缺点,因此一种典型的方法是将基于累加器的实现隐藏在看起来与{{1}完全相同的外观之后}:
rev2
答案 1 :(得分:2)
让我开始吧:
rev2 :: [a] -> [a]
rev2 xs = rev2' xs ???
rev2' :: [a] -> [a] -> [a]
rev2' [] ys = ???
rev2' (x : xs) ys = ???