(>>=)和(>=>)之间的区别

8
我需要澄清(>>=)和(>=>)的区别。
*Main Control.Monad> :type (>>=)                                                                                                                                                               
(>>=) :: Monad m => m a -> (a -> m b) -> m b                                                                                                                                                
*Main Control.Monad> :type (>=>)                                                                                                                                                               
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c 

我知道绑定运算符(>>=),但不明白何时使用(>=>)是有用的。请用简单的玩具示例来解释一下。

编辑:根据@Thomas的评论进行更正。


4
你是如何得出一个是另一个的懒惰版本的?我们应该更正或删除这个资源,因为它是错误的。 - Thomas M. DuBuisson
f >=> g = \x -> f x >>= g - Bergi
嗨,Thomas,请看一下这个框架 https://youtu.be/2jdJGdA7AYs?t=3m30s。 - venu gangireddy
@Thomas 这些东西在视频中的上下文中使用,但我没有理解解释,所以我在这里发布。 - venu gangireddy
3
@venugangireddy 这个视频讲述了惰性IO以及采取行动(例如读取文件、计算值和关闭句柄)的情况。视频中有趣的不是你关注的运算符,而是在withFile范围内与之后发生的print - Thomas M. DuBuisson
在某些应用程序中,withX (h >=> p)withX h >>= p 之间的惰性差异与 >=>>>= 之间的差异无关。这就像 fmap g $!! fmap f $ xfmap (g . f) $!! x 之间的区别一样。 - leftaroundabout
1个回答

12

(>=>) 函数有点像 (.),但它不是处理 a -> b,而是处理 a -> m b

-- Ask the user a question, get an answer.
promptUser :: String -> IO String
promptUser s = putStrLn s >> getLine

-- note: readFile :: String -> IO String

-- Ask the user which file to read, return the file contents.
readPromptedFile :: String -> IO String
readPromptedFile = promptUser >=> readFile

-- Ask the user which file to read,
-- then print the contents to standard output
main = readPromptedFile "Read which file?" >>= putStr

这个例子有点勉强,但它说明了(>=>)。像(.)一样,你不需要它,但通常对于以点无风格编写程序很有用。

请注意,(.)(>=>)具有相反的参数顺序,但还有(<=<),它是flip (>=>)

readPromptedFile = readFile <=< promptUser

谢谢Dietrich,这个运算符有什么名字吗? - venu gangireddy
12
这个运算符的非正式名称是"鱼子运算符";正式地,它被称为从左到右的Kleisli组合运算符。(形如"a -> m b"的函数被称为Kleisli箭头,这是范畴论中的一个概念。) - chepner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接