2017-04-12 49 views
2

今天我在玩>>=,試圖理解monad,並發現了一個有趣的模式。在處理列表monad時,>>=似乎表現得像concatMap。我四處搜尋,試圖找出任何相似之處,特別注意hackage的定義。>> =和concatMap之間的區別

有些事情我想:

[1, 2, 3] >>= (iter 5 id) => [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3]

concatMap (iter 5 id) [1, 2, 3]=> [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3] 

[1, 2, 3] >>= (iter 5 (+5)) => [1,6,11,16,21,2,7,12,17,22,3,8,13,18,23]

concatMap (iter 5 (+5)) [1, 2, 3] => [1,6,11,16,21,2,7,12,17,22,3,8,13,18,23]

iter只是非無限的迭代,

iter i f a = toL $ Data.Sequence.iterateN i f a 
    where 
    toL = Data.Foldable.toList :: Data.Sequence.Seq a -> [a] 

(在repl.it工作,所以進口是搞砸了)。

(>>=)等價於concatMap的列表嗎? 是concatMap的推廣嗎?

+0

見https://en.wikibooks.org/wiki/Haskell/Understanding_monads/List的執行情況進行深入的解釋Monad的列表類型。也是https://wiki.haskell.org/All_About_Monads#List_is_also_a_monad。 – bheklilr

回答

5

是,是concatMap的列表。 >>=對於任何Monad來說只是fmapjoinconcat的推廣)的組合,所以這也是直觀的。

+0

感謝關於加入的一點,我從來沒有真正意識到這一點! –

9

是的,參數翻轉。比較這些類型簽名要帶出的相似性,雖然特殊的列表語法干擾:

Prelude> :t flip concatMap 
flip concatMap :: Foldable t => t a -> (a -> [b]) -> [b] 
Prelude> :t (>>=) 
(>>=)   :: Monad m => m a -> (a -> m b) -> m b 
+2

以前綴形式('Foldable t => ta - >(a - > [] b) - > [] b')編寫列表類型構造函數是合法的,只是沒有人這樣做,因爲它會導致更多的括號(' []([] a)'vs.'[[a]]')。 –

相關問題