Home > OS >  Redefining the drop function in terms of filter or map
Redefining the drop function in terms of filter or map

Time:03-07

I have a homework where I need to redefine the drop function in terms of the map or filter function.

drop n (:xs) = drop (n-1) (xs) drop 3 [1,2,3,4,5] = [4,5]

I have an idea but I'm not sure how to implement it. First you zip the elements of the list (say xs) with [1..] and you get elements of the list paired with these numbers (say (x,y)). Then you somehow try to filter these pairs in such a way that y would be greater than 3.

Then you print out the elements of x from the filtered pairs.

But I struggle to put this idea into code. Any help I can get or suggestions about the idea would be much appreciated.

CodePudding user response:

You have the exact right idea. It's a three step process: (1) zip with an enumerator of some kind, (2) filter based on the index, and (3) map to get rid of the enumerator. The code representing that would look something like this

drop :: Int -> [a] -> [a]
drop n xs = map snd . filter (\(i, _) -> i > n) . zip [1..] $ xs

where snd is the Prelude function defined as

snd :: (a, b) -> b
snd (a, b) = b
  • Related