Monads

Page content

Monad

Prelude> :i Monad
class Applicative m => Monad (m :: * -> *) where
  (>>=) :: m a -> (a -> m b) -> m b
  (>>) :: m a -> m b -> m b
  return :: a -> m a
  {-# MINIMAL (>>=) #-}
  	-- Defined in ‘GHC.Base’

Monad 需要實作兩個 function

  • return
  • >>= (讀作 bind)

return

這裡的 return 和其他語言的 return 很不一樣

return :: a -> m a

m 是

return 把一個 type 是 a 的值包進一個 monadic context (不知道怎麼翻…,單子的框架?) 中

>>= (bind)

>>

接下來是一個輔助的 function

Monad Laws

參考

You Could Have Invented Monads! (And Maybe You Already Have.)

工程化:Javascript中的Monad

參考資料

https://wiki.haskell.org/Typeclassopedia

http://dev.stephendiehl.com/hask/#monads