C9 Lectures: Dr. Erik Meijer - Functional Programming Fundamentals Chapter 7 of 13
Nov 12, 2009 at 2:54 PMAgain nice lecture!
A comment about implementing takeWhile and dropWhile using foldr. These are functions to take or drop elements at the beginning of a list. So, I think it would be easier to implement them using foldl (fold left). Can it be done with foldr? I’m not sure. The drawback to implement them with fold is that they would be useless when dealing with infinite lists. That is because fold(r|l) consume the whole list before producing a result.
Here is my take on both using foldl
takeWhile' :: (a -> Bool) -> [a] -> [a] takeWhile' p = snd . foldl (\(e,v) x -> if e then (e,v) else if p x then (False,v++[x]) else (True,v)) (False,[]) dropWhile' :: (a -> Bool) -> [a] -> [a] dropWhile' p = snd . foldl (\(e,v) x -> if e then (e,v++[x]) else if p x then (True,v) else (False,v++[])) (False,[])