如何在Haskell中没有prelude模块的情况下编写功能下降的代码?

时间:2019-04-12 12:38:05

标签: haskell recursion

我想在Haskell中自己编写一些前奏函数,以更好地理解它并对其进行一些练习。我已经编码了TAKE函数,但是DROP函数存在一些问题。

take1 :: Int -> [a] -> [a]

take1 _ [] = []

take1 0 _ = []

take1 n (x:xs) = x:take1 (n-1) xs 

-- Input: take 5 [1,2,3,4,5,6,7] 

-- Output: [1,2,3,4,5]

--This is the take Function and its working.

drop1 :: Int -> [a] -> [a]

drop1 _ [] = []

drop1 n (x:xs) = x : drop1 (n+1) xs 

-- Input: drop 5 [1,2,3,4,5,6,7,8,9,10] 

-- Output: [6,7,8,9,10] 

-- It´s printing out the whole List and not the wanted result.

1 个答案:

答案 0 :(得分:4)

删除的想法是跳过n的第一项,因此只需递归丢弃,直到达到 0

drop:: Int -> [a] -> [a]
drop _ []     = []
drop 0 xs     = xs
drop n (_:xs) = drop (n-1) xs

您错过的重要基本案例是drop 0 xs = xs,因此,如果我没有放弃的任何内容,我将只退还我得到的。 另外请注意,递归调用中我们递减((n-1))不会递增,否则您将永远无法达到基本情况。