[Haskell-cafe] Re: Hi can u explain me how drop works in Haskell

Fernando Gonzalez nanotitan at gmail.com
Wed Feb 28 14:40:07 EST 2007

iliali16 <iliali16 <at> gmail.com> writes:

> Hi I am trying to implement the function drop in haskell the thing is that I
> I have been trying for some time and I came up with this code where I am
> trying to do recursion:
> drop :: Integer -> [Integer] -> [Integer]
> drop 0 (x:xs) = (x:xs)
> drop n (x:xs)
> 	|n < lList (x:xs) = dropN (n-1) xs :  
> 	|otherwise = []
> So I want to understand how would this work and what exacttly should I put
> as an answer on line 4 couse that is where I am lost. I know I might got the
> base case wrong as well but I don't know what to think for it. I have done
> the lList as a function before writing this one. Thanks to those who can
> help me understand this. Thanks alot in advance! Have a nice day!

I'm curious as to the call to dropN. If you're trying to do recursion then you
should probably call your original drop function (maybe your drop function was
supposed to be called dropN?).

Anyway, I think if you're only testing a single function and you're trying to
come to grips with recursion and other fundamentals of functional programming,
then sidetracking to become familiar with a testing suite such as Quickcheck or
HUnit might be overkill. I prefer the method used by Thomas Hartman in his reply.

However, it should be tweaked a little to really solidify the definition and
verification of your drop function:

drop :: Integral t => t -> [a] -> [a]
drop _ []     = []            -- extra
drop 0 (x:xs) = x:xs
drop n (x:xs) = drop (n-1) xs

main = test
test = do print test1
          print test2
          print test3
          print test4         -- extra

test1 = drop 3 [1,2,3] == []
test2 = drop 2 [1,2,3] == [3]
test3 = drop 0 [1,2,3] == [1,2,3]
test4 = drop 4 [1,2,3] == []  -- extra

Making your function polymorphic over the Integral class for it's first
parameter would keep it working properly whether it receives an Int or an
Integer, a useful property when your function is called by other functions as
it's one less thing to keep track of.

The extra case in the definition keeps the function from failing if n is greater
than 'length (x:xs)'. The extra test (test4) verifies this property.

Fernando Gonzalez

More information about the Haskell-Cafe mailing list