
作者:雷純鋒 授權本站轉載。
Functor、Applicative 和 Monad 是函數式編程中三個極其重要的概念,尤其是 Monad,可謂難倒無數英雄好漢。事實上,它們的概念本身並不複雜,只是很少有文章能講得清楚,往往越描越黑。與眾不同的是,本文從結論出發,層層深入,一步步為你揭開它們的神秘面紗。
說明:本文示例主要採用 Haskell 語言,這是一門純函數式編程語言。至於具體的語法細節,你無需過分糾結,因為它並不影響你對本文的理解。
結論先行
其實,Functor、Applicative 和 Monad 的概念各用一句話就能概括:
所謂 Functor,就是一種實現了 Functor typeclass 的數據類型;
所謂 Applicative,就是一種實現了 Applicative typeclass 的數據類型;
所謂 Monad,就是一種實現了 Monad typeclass 的數據類型。
你可能會問,那 typeclass 又是什麼?當你看到「實現」二字時,想必已經猜到了:
A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. A lot of people coming from OOP get confused by typeclasses because they think they are like classes in object oriented languages. Well, they're not. You can think of them kind of as Java interfaces, only better.
是的,typeclass 類似於 Java 中的接口,或 Objective-C 中的協議。typeclass 裡定義了一些函數,實現一個 typeclass 就是要實現這些函數,而所有實現了該 typeclass 的數據類型,都會擁有這些共同的行為。
那 Functor、Applicative 和 Monad 之間有何關聯,為何總是成組出現?其實,Applicative 是增強版的 Functor——要成為 Applicative,前提是它必須是 Functor;同樣,Monad 是增強版的 Applicative——要成為 Monad,前提是它必須是 Applicative。這個層層遞進的關係,在你看到 typeclass 的定義時便會豁然開朗。
Meet Maybe
在正式介紹三者定義之前,我想先聊一個很有意思的數據類型——Maybe(可類比 Swift 中的 Optional):
The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a), or it is empty (represented as Nothing). Using Maybe is a good way to deal with errors or exceptional cases without resorting to drastic measures such as error.
Maybe 封裝了一個可選值:一個 Maybe a 類型的值,要麼包含一個 a 類型的值(寫作 Just a),要麼為空(寫作 Nothing)。我們可以把 Maybe 想象成一個盒子——盒子裡可能裝著一個 a 類型的值(Just a),也可能是一個空盒子(Nothing)。或者,你也可以把它理解為泛型,比如 Objective-C 中的 NSArray。

data Maybe a = Nothing | Just a
直觀感受一下 Maybe 類型:
ghci> Nothing Nothing ghci> Just 2 Just 2
用盒子模型來理解:Nothing 是一個空盒子;而 Just 2 是一個裝著數值 2 的盒子。

提前劇透:Maybe 同時實現了 Functor、Applicative 和 Monad 三個 typeclass,因此它既是 Functor,又是 Applicative,還是 Monad,具體實現將在後續章節展開。
Functor
在介紹 Functor 之前,先思考一個問題:假設我們有一個值 2:

如何把函數 (+3) 應用到它身上?上過小學的朋友都知道,這就是一次簡單的加法:

ghci> (+3) 2 5
輕鬆搞定。那麼問題來了,如果這個值 2 被放進某個上下文中呢?比如 Maybe,此時它就變成了 Just 2:

這時,我們就不能直接把 (+3) 應用到 Just 2 上了。那麼,如何把一個函數應用到處於上下文中的值呢?

想必你已經猜到,這正是 Functor 的用武之地,詳見下節。
Functor typeclass
先看 Functor typeclass 的定義:
class Functor f where fmap :: (a -> b) -> f a -> f b
其中定義了一個函數 fmap,它把函數 (a -> b) 應用到處於上下文中的值 f a,並返回另一個處於相同上下文中的值 f b。這裡的 f 是類型占位符,代表任意 Functor。
注:fmap 可類比 Swift 中的 map 方法。
Maybe Functor
我們知道 Maybe 就是一個 Functor,它實現了 Functor typeclass。把類型占位符 f 換成具體的 Maybe:
class Functor Maybe where fmap :: (a -> b) -> Maybe a -> Maybe b
因此,對 Maybe 而言,fmap 的功能就是把函數 (a -> b) 應用到 Maybe 上下文中的值 Maybe a,並返回另一個 Maybe 上下文中的值 Maybe b。來看具体实现:
instance Functor Maybe where fmap func (Just x) = Just (func x) fmap func Nothing = Nothing
這裡針對 Maybe 的兩種情況分別處理:若盒子裡有值(Just x),就取出 x,把 func 應用到 x,再將結果裝進一個同類型的新盒子;若盒子為空,則直接返回一個新的空盒子。
看到這裡,你應該已經知道如何把函數應用到上下文中的值了。比如把 (+3) 應用到 Just 2:

ghci> fmap (+3) (Just 2) Just 5
值得一提的是,當我們把 (+3) 應用到空盒子 Nothing 時,得到的仍是一個新的空盒子:

ghci> fmap (+3) Nothing Nothing
Applicative
現在,我們已經能把 (+3) 應用到 Just 2 了。那麼問題又來了,如果函數 (+3) 也處於上下文中呢?比如它變成了 Just (+3):

如何把一個處於上下文中的函數,應用到一個處於上下文中的值?

這正是 Applicative 要解決的事,詳見下節。
Applicative typeclass
同樣,先看定義:
class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b
注意,與 Functor 不同,這裡多了一個類約束 Functor f,意思是:數據類型 f 要實現 Applicative,前提是它必須先實現 Functor,也就是說它必須是一個 Functor。
Applicative 定義了兩個函數:
pure:把一個值 a 放入上下文中;
(<*>):把一個上下文中的函數 f (a -> b) 應用到一個上下文中的值 f a,並返回另一個上下文中的值 f b。
Maybe Applicative
把類型占位符 f 換成具體的 Maybe:
class Functor Maybe => Applicative Maybe where pure :: a -> Maybe a (<*>) :: Maybe (a -> b) -> Maybe a -> Maybe b
於是,對 Maybe 而言,pure 的功能是把一個值 a 放入 Maybe 上下文;而 (<*>) 的功能則是把 Maybe 上下文中的函數 Maybe (a -> b) 應用到 Maybe 上下文中的值 Maybe a,並返回另一個 Maybe 上下文中的值 Maybe b。具體實現如下:
instance Applicative Maybe where pure = Just Nothing _ = Nothing (Just func) something = fmap func something
pure 的實現非常簡單,直接等於 Just 即可。而 (<*>) 的實現同樣需要針對兩種情況分別處理:當裝函數的盒子為空時,直接返回一個新的空盒子;當裝函數的盒子不為空(Just func)時,取出 func,用 fmap 把它應用到那個上下文中的值——這正是 Functor 的功能。
接著看把 Just (+3) 應用到 Just 2 的過程:

ghci> Just (+3) <*> Just 2 Just 5
同樣,當把空盒子 Nothing 應用到 Just 2 時,我們會得到一個新的空盒子:
ghci> Nothing <*> Just 2 Nothing
Monad
到目前為止,我們知道 Functor 的作用是把一個函數應用到上下文中的值:

而 Applicative 的作用是把一個上下文中的函數應用到上下文中的值:

那 Monad 又是什麼呢?其實 Monad 的作用與 Functor 類似,也是把一個函數應用到上下文中的值。區別在於:Functor 應用的是「接收普通值並返回普通值」的函數,而 Monad 應用的是「接收普通值,卻返回一個上下文中的值」的函數:

Monad typeclass
同樣,先看定義:
class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b x >> y = x >>= \_ -> y fail :: String -> m a fail msg = error msg
哇,這是什麼鬼,完全看不懂?別急,聽我細說。Monad 定義了四個函數:return、(>>=)、(>>) 和 fail,其中後兩個 (>>) 和 fail 有默認實現,絕大多數情況下我們都不必重寫。去掉這兩個後,定義可簡化為:
class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b
是不是清爽多了?與 Applicative 一樣,這裡也有類約束 Applicative m,表示要成為 Monad,前提是它必須是 Applicative。此外,return 的功能其實和 Applicative 中的 pure 一樣,只是換了個名字,作用都是把一個值 a 放入上下文;而 (>>=) 的功能,則是把一個「接收普通值 a、返回上下文中的值 m b」的函數 (a -> m b) 應用到上下文中的值 m a,並返回另一個相同上下文中的值 m b。
注:>>= 讀作 bind,學習 ReactiveCocoa 的同學要留意;它可類比 Swift 中的 flatMap 方法。
Maybe Monad
把類型占位符 m 換成具體的 Maybe:
class Applicative Maybe => Monad Maybe where return :: a -> Maybe a (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
相信憑藉盒子模型,你已能輕鬆理解這兩個函數,這裡不再贅述。具體實現如下:
instance Monad Maybe where return x = Just x Nothing >>= func = Nothing Just x >>= func = func x
正如前面所說,return 的實現與 pure 相同,直接等於 Just,功能是將值 x 放入 Maybe 盒子變成 Just x。對於 (>>=),同樣針對兩種情況處理:盒子為空時直接返回新空盒子;盒子不為空(Just x)時取出 x,直接把 func 應用到 x,而 func x 的結果本來就是一個上下文中的值。
來看一個具體例子。先定義 half 函數:接收數字 x,若 x 為偶數,則將 x 除以 2 並放入 Maybe 盒子;若為奇數,則返回空盒子:

half x = if even x then Just (x `div` 2) else Nothing
接著,用 (>>=) 把 half 應用到 Just 20,得到結果 y;再把 half 應用到 y,如此類推:
ghci> Just 20 >>= half Just 10 ghci> Just 10 >>= half Just 5 ghci> Just 5 >>= half Nothing
看出點端倪了嗎?上一步的輸出作為下一步的輸入,只要願意,這個過程可以無限延續。想必你已經想到——這就是鏈式操作。所有操作串聯起來就像一條生產線,每一步都在對輸入進行加工並產生輸出,整個過程可視為對最初的原材料 Just 20 加工,最終產出成品 Nothing:

ghci> Just 20 >>= half >>= half >>= half Nothing
注:鏈式操作只是 Monad 帶來的主要好處之一;另一個本文未展開的好處是,Monad 能自動為我們處理上下文,讓我們只需專注於真正的值。
ReactiveCocoa
現在我們知道 Monad 就是一種實現了 Monad typeclass 的數據類型。那它有什麼實際應用呢?總不能只做理論研究吧。既然如此,就請出 Objective-C 中的神器——ReactiveCocoa,它正是依據 Monad 的概念搭建而成。下面是 RACStream 的繼承結構圖:

RACStream 是 ReactiveCocoa 中最核心的類,它本質上就是一個 Monad:
/// An abstract class representing any stream of values. /// /// This class represents a monad, upon which many stream-based operations can /// be built. /// /// When subclassing RACStream, only the methods in the main @interface body need /// to be overridden. @interface RACStream : NSObject /// Lifts `value` into the stream monad. /// /// Returns a stream containing only the given value. + (instancetype)return:(id)value; /// Lazily binds a block to the values in the receiver. /// /// This should only be used if you need to terminate the bind early, or close /// over some state. -flattenMap: is more appropriate for all other cases. /// /// block - A block returning a RACStreamBindBlock. This block will be invoked /// each time the bound stream is re-evaluated. This block must not be /// nil or return nil. /// /// Returns a new stream which represents the combined result of all lazy /// applications of `block`. - (instancetype)bind:(RACStreamBindBlock (^)(void))block; @end
可以看到,RACStream 中定義了兩個格外眼熟的方法:
+ (instancetype)return:(id)value;
- (instancetype)bind:(RACStreamBindBlock (^)(void))block;
其中,return: 的功能是把值 value 放入 RACStream 上下文;bind: 的功能則是把一個 RACStreamBindBlock 類型的 block 應用到 RACStream 上下文中的值(receiver),並返回另一個 RACStream 上下文中的值。注,RACStreamBindBlock 就是一個「接收普通值、返回 RACStream 上下文中的值」的函數:
/// A block which accepts a value from a RACStream and returns a new instance /// of the same stream class. /// /// Setting `stop` to `YES` will cause the bind to terminate after the returned /// value. Returning `nil` will result in immediate termination. typedef RACStream * (^RACStreamBindBlock)(id value, BOOL *stop);
為加深理解,我們再對比一下 Monad typeclass 的定義:
class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b
把類型占位符 m 換成 RACStream:
class Applicative RACStream => Monad RACStream where return :: a -> RACStream a (>>=) :: RACStream a -> (a -> RACStream b) -> RACStream b
其中,return :: a -> RACStream a 對應 + (instancetype)return:(id)value;,而 (>>=) :: RACStream a -> (a -> RACStream b) -> RACStream b 則對應 - (instancetype)bind:(RACStreamBindBlock (^)(void))block;。前面提過,>>= 讀作 bind。因此,ReactiveCocoa 便有了這樣的玩法:
RACSignal *signal2 = [[[signal1 bind:block1] bind:block2] bind:block3];
Monad 就像 ReactiveCocoa 中的太極,太極生兩儀,兩儀生四象,四象生八卦。至此,我們已領略 ReactiveCocoa 最核心的原理,更多內容將在後續源碼解析中展開,敬請期待。
總結
Functor、Applicative 和 Monad 是什麼:
Functor:實現了 Functor typeclass 的數據類型;
Applicative:實現了 Applicative typeclass 的數據類型;
Monad:實現了 Monad typeclass 的數據類型。
三者之間的關聯:
Applicative 是增強版的 Functor,前提是它必須是 Functor;
Monad 是增強版的 Applicative,前提是它必須是 Applicative。
三者之間的區別:

Functor:用 fmap 把一個函數應用到上下文中的值;
Applicative:用 <*> 把一個上下文中的函數應用到上下文中的值;
Monad:用 >>= 把一個「接收普通值、返回上下文中值」的函數應用到上下文中的值。
此外,我們還介紹了 Maybe 這一看似簡單卻妙趣橫生的數據類型,它同時是 Functor、Applicative 和 Monad。
以上就是本文的全部內容,希望對你有所幫助,Good luck!
參考鏈接
https://learnyouahaskell.com/chapters
https://downloads.haskell.org/~ghc/latest/docs/html/libraries
https://adit.io/posts/2013-04-17-functors,applicatives,and_monads_in_pictures.html