Lud*_*igH 3 monads haskell functor
拥有powershell脚本的背景我首先想到以管道方式思考函数组合是很自然的.这意味着组合的语法应该是fun1 | fun2 | fun3一种psudocode方式.("按顺序应用fun[i]的i'功能在哪里).这个函数的顺序也是你在haskell monadic绑定中找到的.fun1 >>= fun2 >>= fun3.
但是在haskell的其他场合,函数的顺序更像是数学,例如fun3 . fun2 . fun1,或者在函数设置中fmap fun3 . fmap fun2 . fmap fun1.
我非常清楚这些函数在两个例子中有不同的签名,但令我感到困惑的是,结构仍然是相反的.我的解决方法是有时定义一个mmap = flip (>>=)我可以编写的函数mmap fun3 . mmap fun2 . mmap fun1.
那么问题是:
mmap定义?叫什么叫?有没有
mmap定义?叫什么叫?
(>>=) :: Monad m => m a -> (a -> m b) -> m b
Run Code Online (Sandbox Code Playgroud)
因此,您正在寻找具有类型签名的函数:
flip (>>=) :: Monad m => (a -> m b) -> m a -> m b
Run Code Online (Sandbox Code Playgroud)
这实际上就是这个=<<功能.因此,你可以写fun3 =<< fun2 =<< fun1.
为什么绑定被定义为具有参数的运算符,其顺序感觉倒退?
这是因为monadic代码看起来很像命令式代码.例如,请考虑以下事项:
permute2 :: [a] -> [[a]]
permute2 xs = do
x <- xs
xs <- map return xs
return (x:xs)
Run Code Online (Sandbox Code Playgroud)
如果没有它的语法糖,do它将写成:
permute2 :: [a] -> [[a]]
permute2 xs =
xs >>= \x ->
map return xs >>= \xs ->
return (x:xs)
Run Code Online (Sandbox Code Playgroud)
看到相似度?如果我们使用=<<它,它看起来像:
permute2 :: [a] -> [[a]]
permute2 xs = (\x -> (\xs -> return (x:xs)) =<< map return xs) =<< xs
Run Code Online (Sandbox Code Playgroud)
不是很可读吗?