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

ven*_*ddy 8 monads haskell functional-programming

我需要一些关于(>> =)和(> =>)的澄清.

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

我知道bind运算符(>> =),但我没有得到(> =>)有用的上下文.请用简单的玩具例子说明.

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

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

这有点人为,但它说明了这一点(>=>).比如(.),你不需要它,但它通常用于以无点样式编写程序.

请注意,(.)有从对面参数顺序(>=>),但也有(<=<)flip (>=>).

readPromptedFile = readFile <=< promptUser
Run Code Online (Sandbox Code Playgroud)

  • 非正式名称是鱼类运营商; 正式来说,它是从左到右的Kleisli组合运算符.(形式为"a - > mb"的函数称为Kleisli箭头,来自类别理论的概念.) (12认同)