Include nonpositive counts and exhausted input explicitly:
take :: Int -> [a] -> [a]
take n _ | n <= 0 = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
drop :: Int -> [a] -> [a]
drop n xs | n <= 0 = xs
drop _ [] = []
drop n (_:xs) = drop (n-1) xsThe tests on the count precede inspection of the input list. Thus
take 0 undefined = [], while drop 0 undefined = undefined, exactly as these list prefix and list suffix operations require. No element value is inspected merely to traverse the spine.[ref]Haskell 2010 Language Report. Chapter 9, PreludeList: take and drop
Articles by others on the same topic
There are currently no matching articles.