I want to write some prelude functions by myself in Haskell to understand it better and to exercise a bit with it. I already coded the TAKE function but I have some problems with the DROP function.
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. 11 Answer
The idea of drop is to skip the n first items, so just discard them recursively until you reach 0:
drop:: Int -> [a] -> [a] drop _ [] = [] drop 0 xs = xs drop n (_:xs) = drop (n-1) xs The important base case that you miss is drop 0 xs = xs, so if I have nothing to drop I just return what I got. Also note that we decrement ((n-1)) not increment in the recursive call, otherwise you will never reach to the base case.