Skip to content

Instantly share code, notes, and snippets.

@sjoerdvisscher
Last active April 7, 2020 09:41
Show Gist options
  • Save sjoerdvisscher/6204945 to your computer and use it in GitHub Desktop.
Save sjoerdvisscher/6204945 to your computer and use it in GitHub Desktop.
If you have a Functor f with an instance Monoid a => Monoid (f a), f is Applicative!
{-# LANGUAGE QuantifiedConstraints, ScopedTypeVariables #-}
import Data.Monoid
-- Note: fails for instances that don't need the Monoid a or Semigroup a
pureDefault :: forall f a. (Functor f, forall a. Monoid a => Monoid (f a)) => a -> f a
pureDefault a = a <$ (mempty :: f ())
apDefault :: (Functor f, forall a. Semigroup a => Semigroup (f a)) => f (a -> b) -> f a -> f b
apDefault ff fa = (\([f], [a]) -> f a) <$> fmap (\f -> ([f], [])) ff <> fmap (\a -> ([], [a])) fa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment