>> =和concatMap之间的区别

Jac*_*ndt 3 monads haskell

>>=今天我一直在玩,试图了解monad,并找到了一个有趣的模式.使用列表monad时,>>=似乎表现得像concatMap.我四处寻找,试图找到任何相似之处,特别是在hackage的定义中.

我试过的一些事情:

[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]
Run Code Online (Sandbox Code Playgroud)

[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] 
Run Code Online (Sandbox Code Playgroud)

(在repl.it中工作所以进口被搞砸了).

(>>=)相当于concatMap对列表?这是概括concatMap吗?

ja.*_*ja. 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
Run Code Online (Sandbox Code Playgroud)

  • 以前缀形式编写列表类型构造函数是合法的(`Foldable t => ta - >(a - > [] b) - > [] b`),只是没有人这样做,因为它会导致更多的括号(`[ ]([] a)`vs.` [[a]]`). (2认同)

Laz*_*oke 7

是的,(=<<)concatMap列表.对于任何Monad来说,>>=它只是fmapjoin(概括concat)的结合,所以这也是直觉上的.