drop1 n xs | n<0 = error "Use positive numbers"
drop1 _ [] = error "Empty list"
drop1 0 xs = xs
drop1 n xs = drop1 (n-1)(tail1 xs)
My drop1 function checks every time. What can I do to check this only 1 first time? How can I modify this part:
drop1 n xs | n<0 = error "Use positive numbers"
?
CodePudding user response:
You can work with a helper function:
drop1 :: Int -> [a] -> [a]
drop1 n
| n < 0 = error "Use positive numbers"
| otherwise = go n
where go _ [] = error "Empty list"
go 0 xs = xs
go k (_:xs) = go (k-1) xs
The drop1
thus checks once if the value is less than 0
, whereas go
only checks for 0
and values larger than 0
.
Probably you want to swap the two clauses about go _ [] = error "Empty list"
and go 0 xs = xs
, since dropping two items of a list containing two items probably should return an empty list, and not an error.