Monad Transformers

Monad 转换器用于将两个不同的Monad合成为一个Monad。Monad 转换器本身也是一个 Monad。

MaybeT

MaybeT 这个 Monad 转换器通过将 Maybe Monad 封装进其它 Monad来使两者合二为一。

newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }
instance (Monad m) => Monad (MaybeT m) where
return = lift . return
x >>= f = MaybeT $ do
v <- runMaybeT x
case v of
Nothing -> return Nothing
Just y -> runMaybeT (f y)
  • newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }

    MaybeT 类型是个 newtype,也就是对现有类型的封装。该类型有两个类型参数:内部 Monad 类型 m 以及基础 Monad Maybe 的参数类型 a。

    MaybeT m a 封装了一个 m (Maybe a) 类型的值,通过 runMaybeT 字段可以取出这个值。
  • instance (Monad m) => Monad (MaybeT m) where

    如果 m 是个 Monad,那么 MaybeT m 也是一个 Monad。

    对比 Monad 类型类的定义,可知 return 函数的类型签名为:

    return :: a -> MaybeT m a

    大致相当于 a -> m (Maybe a)

    而 bind 操作符的类型签名为:

    (>>=) :: MaybeT m a -> (a -> MaybeT m b) -> MaybeT m b

    大致相当于 m (Maybe a) -> (a -> m (Maybe b)) -> m (Maybe b)
  • return = lift . return

    return 函数首先将类型为 a 的值封装进内部 Monad m 中,然后通过 lift 函数将它封装进 MaybeT 这个 Monad 转换器之中。

    这里左侧的 return 是 MaybeT 这个 Monad 的 return,而右侧的 return 是内部 Monad m 的 return。
  • x >>= f = MaybeT $ do

    对比函数签名,可知 x 的类型是 MaybeT m a,大致相当于 m (Maybe a)

    而 f 的类型是 a -> MaybeT m b,大致相当于 a -> m (Maybe b)
  • v <- runMaybeT x

    对比 x 的类型,可知 v 的类型是 Maybe a

    这是因为 runMaybeT 函数让 x 脱离了 MaybeT Monad, 而 <- 运算符又让 runMaybeT x 脱离了内部 Monad m。
  • case v of
  • Nothing -> return Nothing

    这里 return 是内部 Monad m 的 return,所以 return Nothing 的类型是 m (Maybe a)。
  • Just y -> runMaybeT (f y)

    f 的类型是 a -> MaybeT m b

    所以 f y 的类型是 MaybeT m b

    而 runMaybeT (f y) 的类型是 m (Maybe b)
Prelude> :m +Control.Monad.Trans.Maybe
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (return 1 :: MaybeT IO Int)
Just 1
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (return 1 :: MaybeT [] Int)
[Just 1]
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (return 1 :: MaybeT IO Int) >>= \x -> return (x * 2)
Just 2
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (return 1 :: MaybeT [] Int) >>= \x -> return (x * 2)
[Just 2]

lift

class MonadTrans t where
lift :: (Monad m) => m a -> t m a instance MonadTrans MaybeT where
lift = MaybeT . liftM Just

lift 函数的作用为提升已经被封装进内部 Monad 类型 m 的值,让后者进一步被封装进 Monad 转换器 t 类型中。

对于 MaybeT 这个 Monad 转换器,lift 函数的具体实现为:

首先调用 liftM Just 把内嵌在内部 Monad m 中的值装入Maybe Monad,

然后调用 MaybeT 构造器将整个值装入MaybeT Monad。

Prelude Control.Monad.Trans.Maybe Control.Monad.Trans> runMaybeT $ return 1 >>= lift . print
1
Just ()
Prelude Control.Monad.Trans.Maybe Control.Monad.Trans> runMaybeT $ return 1 >>= \x -> do {lift(print x); return (x * 2)}
1
Just 2
Prelude Control.Monad.Trans.Maybe Control.Monad.Trans> runMaybeT $ return 1 >>= lift . (\x -> [x, x + 1])
[Just 1,Just 2]
证明 MaybeT m 符合 Monad 法则。
1. return a >>= f ≡ f a
return a >>= f
≡ (lift . return) a >>= f
≡ lift (m a) >>= f
≡ (MaybeT . liftM Just) (m a) >>= f
≡ MaybeT (m (Just a)) >>= f
≡ MaybeT $ runMaybeT (f a)
≡ f a
2. m >>= return ≡ m
MaybeT (m (Just x)) >>= return
≡ MaybeT $ runMaybeT (return x)
≡ MaybeT (m (Just x))
MaybeT (m Nothing) >>= return
≡ MaybeT $ (return Nothing)
≡ MaybeT (m Nothing)
3. (m >>= f) >>= g ≡ m >>= (\x -> f x >>= g)
(MaybeT (m (Just x)) >>= f) >>= g ≡ f x >>= g
(MaybeT (m Nothing) >>= f) >>= g ≡ MaybeT (m Nothing) >>= g ≡ MaybeT (m Nothing)
MaybeT (m (Just x) >>= (\x -> f x >>= g) ≡ (\x -> f x >>= g) x ≡ f x >>= g
MaybeT (m Nothing) >>= (\x -> f x >>= g) ≡ MaybeT (m Nothing)

liftIO

class (Monad m) => MonadIO m where
liftIO :: IO a -> m a instance MonadIO IO where
liftIO = id instance (MonadIO m) => MonadIO (MaybeT m) where
liftIO = lift . liftIO

liftIO 函数的作用为提升已经被封装进 IO Monad 的值,让后者进一步被封装进 Monad 转换器 m 类型中。

(前提是Monad 转换器 m 类型必须内部封装了 IO Monad。)

对于 MaybeT IO 这个 Monad 转换器,liftIO 作用等同于 lift。

Prelude Control.Monad.Trans.Maybe Control.Monad.Trans> runMaybeT $ return 1 >>= liftIO . print
1
Just ()
Prelude Control.Monad.Trans.Maybe Control.Monad.Trans> runMaybeT $ return 1 >>= \x -> do {liftIO(print x); return (x * 2)}
1
Just 2

lift 与 liftIO 的法则

1. lift . return ≡ return
liftIO . return ≡ return
2. lift (m >>= f) ≡ lift m >>= (lift . f)
liftIO (m >>= f) ≡ liftIO m >>= (liftIO . f)
证明 MaybeT 中 lift 函数的定义符合 lift 的法则。
1. lift . return ≡ return
根据 MaybeT 中 return 函数的定义
return ≡ lift . return
2. lift (m >>= f) ≡ lift m >>= (lift . f)
假设 m = n a 并且 f a = n b
于是 m >>= f = n b
lift (m >>= f)
≡ MaybeT . liftM Just $ m >>= f
≡ MaybeT . liftM Just $ n b
≡ MaybeT (n (Just b))
lift m >>= (lift . f)
≡ (MaybeT . liftM Just $ m) >>= (MaybeT . liftM Just . f)
≡ (MaybeT (n (Just a))) >>= (\x -> MaybeT . liftM Just . f $ x)
≡ MaybeT $ runMaybeT $ MaybeT . liftM Just . f $ a
≡ MaybeT $ runMaybeT $ MaybeT . liftM Just $ n b
≡ MaybeT $ runMaybeT $ MaybeT (n (Just b))
≡ MaybeT (n (Just b))

MaybeT 是 Functor 也是 Applicative

instance (Functor m) => Functor (MaybeT m) where
fmap f = mapMaybeT (fmap (fmap f)) mapMaybeT :: (m (Maybe a) -> n (Maybe b)) -> MaybeT m a -> MaybeT n b
mapMaybeT f = MaybeT . f . runMaybeT instance (Functor m, Monad m) => Applicative (MaybeT m) where
pure = lift . return
mf <*> mx = MaybeT $ do
mb_f <- runMaybeT mf
case mb_f of
Nothing -> return Nothing
Just f -> do
mb_x <- runMaybeT mx
case mb_x of
Nothing -> return Nothing
Just x -> return (Just (f x))
fmap f x
= mapMaybeT (fmap (fmap f)) x
= MaybeT . (fmap (fmap f)) . runMaybeT $ x
= MaybeT . (fmap (fmap f)) $ m (Maybe a)
= MaybeT (n (Maybe b))
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (*2) <$> (return 1 :: MaybeT IO Int)
Just 2
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (*2) <$> (return 1 :: MaybeT [] Int)
[Just 2]
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (*) <$> (return 1 :: MaybeT IO Int) <*> return 2
Just 2
Prelude Control.Monad.Trans.Maybe> runMaybeT $ (*) <$> (return 1 :: MaybeT [] Int) <*> return 2
[Just 2]

MaybeT 是 Alternative 也是 MonadPlus

instance (Functor m, Monad m) => Alternative (MaybeT m) where
empty = MaybeT (return Nothing)
x <|> y = MaybeT $ do
v <- runMaybeT x
case v of
Nothing -> runMaybeT y
Just _ -> return v instance (Monad m) => MonadPlus (MaybeT m) where
mzero = MaybeT (return Nothing)
mplus x y = MaybeT $ do
v <- runMaybeT x
case v of
Nothing -> runMaybeT y
Just _ -> return v
Prelude Control.Monad.Trans.Maybe Control.Applicative> runMaybeT $ (empty :: MaybeT IO Int) <|> return 2
Just 2
Prelude Control.Monad.Trans.Maybe Control.Monad> runMaybeT $ (mzero :: MaybeT IO Int) `mplus` return 2
Just 2

应用实例

import Control.Monad             (guard)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT) import Data.Char funA :: MaybeT IO String
funA = do
lift $ putStrLn "What is your name?"
name <- lift getLine
guard $ not (null name)
return name funB :: String -> MaybeT IO String
funB name = do
lift $ putStrLn ("hello, " ++ name)
lift $ putStrLn "how old are you?"
age <- lift getLine
guard (all isDigit age)
return age main :: IO (Maybe String)
main = runMaybeT $ do
a <- funA
funB a
*Main> main
What is your name?
Steven
hello, Steven
how old are you?
20
Just "20"
*Main> main
What is your name?
Steven
hello, Steven
how old are you? Just ""
*Main> main
What is your name? Nothing

Haskell语言学习笔记(22)MaybeT的更多相关文章

  1. Haskell语言学习笔记(88)语言扩展(1)

    ExistentialQuantification {-# LANGUAGE ExistentialQuantification #-} 存在类型专用的语言扩展 Haskell语言学习笔记(73)Ex ...

  2. Haskell语言学习笔记(79)lambda演算

    lambda演算 根据维基百科,lambda演算(英语:lambda calculus,λ-calculus)是一套从数学逻辑中发展,以变量绑定和替换的规则,来研究函数如何抽象化定义.函数如何被应用以 ...

  3. Haskell语言学习笔记(69)Yesod

    Yesod Yesod 是一个使用 Haskell 语言的 Web 框架. 安装 Yesod 首先更新 Haskell Platform 到最新版 (Yesod 依赖的库非常多,版本不一致的话很容易安 ...

  4. Haskell语言学习笔记(20)IORef, STRef

    IORef 一个在IO monad中使用变量的类型. 函数 参数 功能 newIORef 值 新建带初值的引用 readIORef 引用 读取引用的值 writeIORef 引用和值 设置引用的值 m ...

  5. Haskell语言学习笔记(39)Category

    Category class Category cat where id :: cat a a (.) :: cat b c -> cat a b -> cat a c instance ...

  6. Haskell语言学习笔记(72)Free Monad

    安装 free 包 $ cabal install free Installed free-5.0.2 Free Monad data Free f a = Pure a | Free (f (Fre ...

  7. Haskell语言学习笔记(44)Lens(2)

    自定义 Lens 和 Isos -- Some of the examples in this chapter require a few GHC extensions: -- TemplateHas ...

  8. Haskell语言学习笔记(38)Lens(1)

    Lens Lens是一个接近语言级别的库,使用它可以方便的读取,设置,修改一个大的数据结构中某一部分的值. view, over, set Prelude> :m +Control.Lens P ...

  9. Haskell语言学习笔记(92)HXT

    HXT The Haskell XML Toolbox (hxt) 是一个解析 XML 的库. $ cabal install hxt Installed hxt-9.3.1.16 Prelude&g ...

随机推荐

  1. HBase的BlockCache

    BlockCache 首先要明白Block,在HBase里面存储的最小单元:在memstore向硬盘刷的时候,如果目标block的大小+size之后大于MAX_SIZE,将会新创建一个block来存储 ...

  2. Hyper-V 虚拟机连网

    参考:http://www.cnblogs.com/chenxizhang/p/3188005.html(个人推荐) 参考:http://blog.csdn.net/elvis_0123/articl ...

  3. STL查找序列中处于某一大小范围内的元素个数

    还是头条的笔试题(咦?),问题最后转换成这样的形式: 输入:不包含重复元素的有序数组a[N]以及上下界low, high; 输出:数组a[N]中满足元素处于闭区间[low,high]内(即low &l ...

  4. DDA画线算法

    #include<stdio.h> #include"graphics.h" #include<math.h> #include<stdlib.h&g ...

  5. jstack可以定位到线程堆栈

    java命令--jstack 工具 JVM调优之jstack找出最耗cpu的线程并定位代码 jstack可以定位到线程堆栈,根据堆栈信息我们

  6. 小甲鱼-003 python插曲值变量和字符串

    变量名就像现实生活人们的名字,把一个值赋值给一个名字时,他会存储在内存中,称之为变量variable,在大多数语言中,都把这种行为成为"给变量赋值"或"把值存储在变量中& ...

  7. Eclipse里面的Maven项目打包(Maven build)

    eclipse里面执行maven build打包的时候,如何设置参数? 主要就是设置一个goals

  8. C++多线程同步之Semaphore(信号量)

    一.线程间同步的几种方式 从上篇博文中可以发现,当多个线程对同一资源进行使用时,会产生“争夺”的情况,为了避免这种情况的产生,也就出现了线程间的同步这个技术.线程间的同步有多种方式,在接下来的博文中我 ...

  9. MAN 手册各章节功能介绍及快捷键键位整理

    前言   Man 手册页(Manua pages ,缩写man page) 是在linux操作系统在线软件文档的一种普遍形式.内容包括计算机程序库和系统调用等命令的帮助手册. 手册页是用troff排版 ...

  10. diskspd的使用

    参数翻译 可测试目标: file_path 文件abc.file #<physical drive number> #1为第一块物理磁盘[谨慎,别拿系统盘测试,一般用于准备投入的数据磁盘测 ...