Haskell学习笔记 -- Monads

Monads

翻译叫 “单子”

或者 “一个自函子上的幺半群”

好吧除了让人费解没有什么用

 

同样举一个书上的例子

data Expr = Val Int | Div Expr Expr

eval :: Expr -> Maybe Int
eval (Val n) = Pure n
eval (Div x y) = pure safediv <*> eval x <*> eval y

可以看出这个类型是错的 它得到了一个Maybe (Maybe Int)

safediv :: Int -> Int -> Maybe Int

 (>==) :: Maybe a -> (a -> Maybe b) -> Maybe b

mx >>= f = case mx of 
                    Nothing -> Nothing
                    Just x -> f x

eval (Val n) = Just n
eval (Div x y) = eval x >> = \n -> 
                 eval y >> = \m ->
                 safediv n m

等价的好看写法(语法糖):

m1 >>= \x1 ->
m2 >>= \x2 -> 
...
mn >>= \xn ->
f x1 x2 .. xn

Equals 

do 
   x1 <- m1 
   x2 <- m2 
   ...
   xn <- mn 
   f x1 x2 .. xn

 

栗子:

eval (Div x y) = do
                    n <- eval x
                    m <- eval y
                    safediv n m
instance Monad Maybe where
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= _ =Nothing
(Just x) >>= f = f x

instance Monad [] where
(>>=) :: [a] -> (a -> [b] ) -> [b]
xs >>= f = [y |  x <- xs , y <- f x ]

  

来点应用(有些懵了

pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do 
                x <- xs 
                y <- ys
                return (x,y)

return (x,y) = pure (x,y)  =  [(x,y)] 

posted @ 2021-11-13 20:37  liankewei123456  阅读(51)  评论(0编辑  收藏  举报