2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DefaultSignaturesを用いたMonadの理想的な定義

Posted at

こういう認識で合ってます?

{-# LANGUAGE DefaultSignatures #-}                         
                                                           
import Prelude hiding (Functor(..), Monad(..))
                                                           
class Functor m where                                      
  fmap :: (a -> b) -> m a -> m b                           
  default fmap :: Applicative m => (a -> b) -> m a -> m b  
  fmap f v = pure f <$> v
                                                           
class Functor m => Applicative m where                     
  pure :: a -> m a                                         
  default pure :: Monad m => a -> m a                      
  pure = return                                            
                                                           
  (<$>) :: m (a -> b) -> m a -> m b
  default (<$>) :: Monad m => m (a -> b) -> m a -> m b
  a <$> b = a >>= \f -> b >>= \v -> return (f v)

class Applicative m => Monad m where
  return :: a -> m a
  (>>=) :: m a -> (a -> m b) -> m b

instance Monad [] where
  return a = [a]
  m >>= f = concatMap f m
instance Applicative []
instance Functor []

main :: IO ()
main = do
  print $ [(+1), (*2)] <$> [1, 2, 3]
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?