Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Control.Monad stuff in Applicative
import Control.Applicative
-- Control.Monad stuff in Applicative
-- Data.Traversable has generalized version
mapA :: Applicative f => (a -> f b) -> [a] -> f [b]
mapA f xs = sequenceA (map f xs)
mapA_ :: Applicative f => (a -> f b) -> [a] -> f ()
mapA_ f xs = sequenceA_ (map f xs)
sequenceA :: Applicative f => [f a] -> f [a]
sequenceA as = foldr (liftA2 (:)) (pure []) as
sequenceA_ :: Applicative f => [f a] -> f ()
sequenceA_ as = foldr (*>) (pure ()) as
-- (=<<) :: Monad m => (a -> m b) -> m a -> m b
-- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
-- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
-- impossible
foreverA :: Applicative f => f a -> f b
foreverA a = a *> foreverA a
-- join :: Monad m => m (m a) -> m a
-- impossible
asum :: Alternative f => [f a] -> f a
asum as = foldl (<|>) empty as
filterA :: Applicative f => (a -> f Bool) -> [a] -> f [a]
filterA f xs = foldr consA (pure []) xs
where
consA x a = liftA2 (addIf x) (f x) a
addIf x b xs = if b then x : xs else xs
mapAndUnzipA :: Applicative f => (a -> f (b, c)) -> [a] -> f ([b], [c])
mapAndUnzipA f xs = fmap unzip $ mapA f xs
zipWithA :: Applicative f => (a -> b -> f c) -> [a] -> [b] -> f [c]
zipWithA f xs ys = sequenceA (zipWith f xs ys)
zipWithA_ :: Applicative f => (a -> b -> f c) -> [a] -> [b] -> f ()
zipWithA_ f xs ys = sequenceA_ (zipWith f xs ys)
-- foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
-- foldM_ :: Monad m => (a -> b -> m a) -> a -> [b] -> m ()
-- impossible
replicateA :: Applicative f => Int -> f a -> f [a]
replicateA n a = sequenceA (replicate n a)
replicateA_ :: Applicative f => Int -> f a -> f ()
replicateA_ n a = sequenceA_ (replicate n a)
guardA :: Alternative f => Bool -> f ()
guardA b = unlessA b empty
whenA :: Applicative f => Bool -> f () -> f ()
whenA b a = if b then a else pure ()
unlessA :: Applicative f => Bool -> f () -> f ()
unlessA b a = if b then pure () else a
-- liftM :: Monad m => (a1 -> r) -> m a1 -> m r
-- liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
-- liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
-- liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
-- liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
-- same as liftA*
-- ap :: Monad m => m (a -> b) -> m a -> m b
-- same as <*>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment