[Haskell-beginners] Use of (n + 1) as parameter - is it more efficient?

Vikraman vikraman.choudhury at gmail.com
Fri Dec 20 18:25:25 UTC 2013


On Fri, Dec 20, 2013 at 06:00:08PM +0000, Angus Comber wrote:
> I created my own drop' function like this:
> 
> drop' :: Int -> [a] -> [a]
> drop' 0 xs     = xs
> drop' n []     = []
> drop' n (x:xs) = drop' (n - 1) xs
> 
> 
> But in the Haskell book I am reading it is written like this:
> 
> drop' :: Int -> [a] -> [a]
> drop' 0 xs             = xs
> drop' (n + 1) []       = []
> drop' (n + 1) (x:xs) = drop' n xs
> 
> My version seems to work but I am concerned about my third line (drop' n []
>     = []).  Is that a problem?
> 
> Why does this author use n + 1 as a parameter as opposed to n - 1 like I do
> in body?
> 
> Or does it make no difference?

Using (n + 1) in the pattern match will cause the match to fail for
negative numbers. But this would also need NPlusKPatterns.

Note that in your implementation, negative values will result in an
empty list, which is different from the GHC.List version.

drop n xs     | n <= 0 =  xs
drop _ []              =  []
drop n (_:xs)          =  drop (n-1) xs

You can easily find this out using quickcheck.

λ> quickCheck $ \n xs -> drop' n xs == drop n xs

-- 
Vikraman
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 230 bytes
Desc: PGP signature
URL: <http://www.haskell.org/pipermail/beginners/attachments/20131220/b6fa72c5/attachment.sig>


More information about the Beginners mailing list