This post originated from an RSS feed registered with Java Buzz
by Elliotte Rusty Harold.
Original Post: foldr Starts at the Head
Feed Title: Mokka mit Schlag
Feed URL: http://www.elharo.com/blog/feed/atom/?
Feed Description: Ranting and Raving
It took me long enough to realize that foldr still moves from the beginning to the end of a list. Somehow I thought it started at the right (i.e. the tail) of the list. Once I realized that Exercise 7 was easy:
Write your own definition of the standard takeWhile function, first using explicit recursion, and then foldr.
myTakeWhile :: (a -> Bool) -> [a] -> [a]
myTakeWhile _ [] = []
myTakeWhile f (x:xs) = if (f x)
then x : (myTakeWhile f xs)
else []
fMyTakeWhile :: (a -> Bool) -> [a] -> [a]
fMyTakeWhile f (xs) = foldr step [] xs
where step x ys | f x = x : ys
| otherwise = []