foldr exercises

I implemented some common ruby list operations in haskell using foldr:

import Data.Maybe
-- find f [] = Nothing
-- find f (x:xs) = if f x then Just x else find f xs
find f = foldr (\a b -> if f a then Just a else b) Nothing

-- select f [] = []
-- select f (x:xs) = (if f x then [x] else []) ++ select f xs
select f = foldr (\a b -> if f a then a:b else b) []

-- collect f [] = []
-- collect f (x:xs) = (f x) : (collect f xs)
collect f = foldr (\a b -> f a : b) []

main = do
  putStrLn $ show $ find (==1) (\x -> x == 1) [3, 3, 5, 6, 2]
  putStrLn $ show $ find (==1) (\x -> x == 1) [3, 3, 5, 6, 2, 1]
  putStrLn $ show $ select (==1) (\x -> x == 1) [2,3,3,33]
  putStrLn $ show $ select (==1) (\x -> x == 1) [2,3,3,33,1]
  putStrLn $ show $ collect (*2) (\x -> x * 2) [1,2,3]
 
The commented out lines are the normal way of implementing the function while the line below is the foldr way. All 3 of these functions are already available in the the standard library Data.List as find, filter, and map respectively.

Update: made use of sections to make the code prettier.

blog comments powered by Disqus