Difference between revisions of "99 questions/Solutions/16"

From HaskellWiki
Jump to navigation Jump to search
 
(a slight variation using guards)
Line 13: Line 13:
 
</haskell>
 
</haskell>
   
or an alternative iterative solution:
+
An alternative iterative solution:
  +
 
<haskell>
 
<haskell>
 
dropEvery :: [a] -> Int -> [a]
 
dropEvery :: [a] -> Int -> [a]
Line 22: Line 23:
 
</haskell>
 
</haskell>
   
or yet another iterative solution which divides lists using Prelude:
+
Yet another iterative solution which divides lists using Prelude:
  +
 
<haskell>
 
<haskell>
 
dropEvery :: [a] -> Int -> [a]
 
dropEvery :: [a] -> Int -> [a]
Line 29: Line 31:
 
</haskell>
 
</haskell>
   
or using zip:
+
A similar approach using guards:
  +
  +
<haskell>
  +
dropEvery :: [a] -> Int -> [a]
  +
dropEvery xs n
  +
| length xs < n = xs
  +
| otherwise = take (n-1) xs ++ dropEvery (drop n xs) n
  +
</haskell>
  +
  +
Using zip:
  +
 
<haskell>
 
<haskell>
 
dropEvery n = map snd . filter ((n/=) . fst) . zip (cycle [1..n])
 
dropEvery n = map snd . filter ((n/=) . fst) . zip (cycle [1..n])

Revision as of 20:01, 15 July 2010

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

dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery (x:xs) n = dropEvery' (x:xs) n 1 where
    dropEvery' (x:xs) n i = (if (n `divides` i) then
        [] else
        [x])
        ++ (dropEvery' xs n (i+1))
    dropEvery' [] _ _ = []
    divides x y = y `mod` x == 0

An alternative iterative solution:

dropEvery :: [a] -> Int -> [a]
dropEvery list count = helper list count count
  where helper [] _ _ = []
        helper (x:xs) count 1 = helper xs count count
        helper (x:xs) count n = x : (helper xs count (n - 1))

Yet another iterative solution which divides lists using Prelude:

dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery list count = (take (count-1) list) ++ dropEvery (drop count list) count

A similar approach using guards:

dropEvery :: [a] -> Int -> [a]
dropEvery xs n
  | length xs < n = xs
  | otherwise     = take (n-1) xs ++ dropEvery (drop n xs) n

Using zip:

dropEvery n = map snd . filter ((n/=) . fst) . zip (cycle [1..n])