Skip to content

Instantly share code, notes, and snippets.

@YusukeHosonuma
Created May 8, 2016 13:19
Show Gist options
  • Save YusukeHosonuma/13d83bee3c9dd01863b6c020336b4294 to your computer and use it in GitHub Desktop.
Save YusukeHosonuma/13d83bee3c9dd01863b6c020336b4294 to your computer and use it in GitHub Desktop.
Haskell - implement map and filter functions by recursion and foldr versions.
-- | recursion version
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = f x : map' f xs
filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' f (x:xs)
| f x = x : (filter' f xs)
| otherwise = filter' f xs
-- | foldr version
map'' :: (a -> b) -> [a] -> [b]
map'' f = foldr (\x acc -> (f x) : acc) []
filter'' :: (a -> Bool) -> [a] -> [a]
filter'' p = foldr (\x acc -> if p x then x : acc else acc) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment