Skip to content

Instantly share code, notes, and snippets.

@rgrinberg
Created January 12, 2017 17:36
Show Gist options
  • Save rgrinberg/da2a92c050722ba8d67ec3bcd00d3135 to your computer and use it in GitHub Desktop.
Save rgrinberg/da2a92c050722ba8d67ec3bcd00d3135 to your computer and use it in GitHub Desktop.
mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
mapM' _ [] = return []
mapM' f (x : xs) = do
y <- f x
ys <- mapM' f xs
return (y : ys)
mapM'' :: Monad m => (a -> m b) -> [a] -> m [b]
mapM'' _ [] = return []
mapM'' f (x : xs) =
f x >>= \y ->
mapM'' f xs >>= \ys ->
return (y : ys)
ex1 = mapM' (\a -> [a, a]) [1, 0]
-- [[1,0],[1,0],[1,0],[1,0]]
ex2 = mapM' (\x -> Just x) [1, 0]
-- Just [1, 0]
ex3 = mapM' (\x -> if x > 0 then Just x else Nothing) [10, -1, -2, 5, 6]
-- Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment