Drop the nth item from the list

I taught myself Haskell for a month or so, and today I read the solution to the 16th problem and came up with a question.

Here is the link: http://www.haskell.org/haskellwiki/99_questions/Solutions/16

Basically, this question asks for a function that removes each element of N from the list. For instance,

*Main> dropEvery "abcdefghik" 3

"abdeghk"

First solution in link

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

My question is: why does dropEvery determine the case of empty lists, while dropEvery 'can take care of an empty list? I think itโ€™s dropEvery [] _ = []possible to simply eliminate and modify a few other suggestions, as the following should work exactly the same as above and look shorter.

dropEvery :: [a] -> Int -> [a]
dropEvery xs n = dropEvery' 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

Can someone help me figure this out?

+5
source share
1 answer

, , , . QuickCheck, .


import Test.QuickCheck

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

dropEvery2 :: [a] -> Int -> [a]
dropEvery2 xs n = dropEvery' 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

theyAreSame xs n = (dropEvery xs n) == (dropEvery2 xs n)
propTheyAreSame xs n = n > 0 ==> theyAreSame xs n

ghci

*Main> quickCheck propTheyAreSame 
+++ OK, passed 100 tests.

*Main> dropEvery [] 0
[]
*Main> dropEvery2 [] 0
[]
*Main> dropEvery [] undefined
[]
*Main> dropEvery2 [] undefined
[]

, .

, :

  • Quickcheck .
  • .:)
+7

All Articles