Problem 16

99 Haskell Problems

Problem 16

(**) Drop every N’th element from a list.

Example:

* (drop '(a b c d e f g h i k) 3)
(A B D E G H K)

Example in Haskell:

*Main> dropEvery "abcdefghik" 3
"abdeghk"

Solution:

dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery x 0 = x
dropEvery x n = dropEveryC x n 1

dropEveryC [] _ _ = []
dropEveryC (x:xs) n c
 | n == c = dropEveryC xs n 1
 | otherwise = x:(dropEveryC xs n (c+1))

Looking at the solution, there are many different ways to do this. A really similar but cleaner way to do it is to start using where so that the helper function is no longer visible outside of the main function:

dropEvery :: [a] -> Int -> [a]
dropEvery xs n = helper xs n
  where helper [] _ = []
        helper (x:xs) 1 = helper xs n
        helper (x:xs) k = x:helper xs (k-1)
The scope of helper only exist inside dropEvery so the name n from dropEvery can be use inside helper function as in line 2 of the patten matching while the function helper can’t be call by other functions.
Advertisements