仅使用 monadic 绑定语法表达 do 块 [英] Expressing do block using only monadic bind syntax

查看:19
本文介绍了仅使用 monadic 绑定语法表达 do 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Haskell 中的 do 块只是 monadic 绑定运算符的某种语法糖.例如,可以转换

As far as I know, do blocks in Haskell are just some kind of syntactic sugar for monadic bind operators. For example, one could convert

main = do f <- readFile "foo.txt"
          print f
          print "Finished"

main = readFile "foo.txt" >>= print >> print "Finished"

是否可以将所有 do 块转换为绑定语法?例如,多次使用 f 的这个块怎么样:

Can all do blocks be converted to bind syntax? What about, for example, this block where f is used multiple times:

main = do f <- readFile "foo.txt"
          print $ "prefix " ++ f
          print $ f ++ " postfix"

假设我们在 IO monad 中,不可能简单地执行两次 readFile 计算.这个例子(如果可能的话)如何仅使用绑定语法来表达?

Assuming we are in the IO monad, it is not possible to simply execute the readFile computation twice. How can this example (if possible at all) expressed using only bind syntax?

我认为使用 Control.Monad 不是解决方案,因为它内部使用了 do 块.

I think using Control.Monad is no solution, because it internally uses do blocks.

我认为可以使用箭头来表达这一点(使用 &&&)——也许在这种情况下,只有箭头可以用作 monad 的泛化?

I think it it's possible to express this using arrows (using &&&) -- maybe this is a case where only arrows can be used as a generalization of monads?

请注意,这个问题不是关于上面的特殊例子,而是关于在像 print 这样的 monadic 表达式中多次使用计算结果的一般情况.

Note that this question is not about the special examples above but about the general case of the result of a computation being used multiple times in monadic expressions like print.

推荐答案

是的,都可以转换成bind语法;实际上,它们是由编译器内部转换的.

Yes, all of them can be converted to bind syntax; in fact, they are converted internally by the compiler.

我希望你的例子的这个翻译能给你提示:

I hope this translation of your example gives you the hint:

main = readFile "foo.txt" >>= f ->
       (print $ "prefix " ++ f) >>
       (print $ f ++ " postfix")

这篇关于仅使用 monadic 绑定语法表达 do 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆