(>>=) 和 (>=>) 的区别
difference between (>>=) and (>=>)
我需要关于 (>>=) 和 (>=>) 的一些说明。
*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 评论进行更正
(>=>)
函数有点像 (.)
,但它不是使用 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
我需要关于 (>>=) 和 (>=>) 的一些说明。
*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 评论进行更正
(>=>)
函数有点像 (.)
,但它不是使用 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