我对编程和练习编写函数还很陌生,我试图扭转 Prelude 下降的影响;
drop :: Int -> [a] -> [a]
drop 0 [] = []
drop 0 (x:xs) = x:xs
drop n [] = []
drop n (x:xs) = drop (n-1) xs
进入我最初命名为dropR的东西。
dropR :: Int -> [a] -> [a] -- drops from the right of the list
dropR 0 [] = []
dropR 0 (x:xs) = x:xs
dropR n [] = []
dropR n (x:xs) = reverse (drop (n-1) (reverse xs ++ [x]))
不幸的是,这不起作用,因为输入dropR 2 [1,2,3,4,5]
返回[1,2,3,4]
而不是[1,2,3]
我希望的那样。使用 drop 2,我会在列表中得到 3 个值而不是 4 个。我将函数更改为;
dropR :: Int -> [a] -> [a] -- drops from the right of the list
dropR 0 [] = []
dropR 0 (x:xs) = x:xs
dropR n [] = []
dropR n (x:xs) = reverse (drop n (reverse xs ++ [x]))
它以我想要的方式工作,但我不明白为什么第一个不起作用。我认为它只会反转列表并获取与常规 drop 相同数量的值,之后我可以反转它。
为什么 drop 需要drop (n-1)
而我的 dropR 只需要drop n
?它是因为 drop 中的递归而不是 dropR 中的递归而发生的吗?