问题描述
据我所知,Haskell中的 do
块仅仅是一元绑定操作符的某种语法糖。例如,可以转换为 main = do f< - readFilefoo.txt
print f
printFinished
至
main = readFilefoo.txt>> = print>>打印已完成
所有都可以
块被转换为绑定语法?例如,如何使用 f
多次使用的块:
main = do f< - readFilefoo.txt
print $prefix++ f
print $ f ++postfix
假设我们在IO monad中,不可能简单地执行 readFile
两次计算。这个例子(如果可能的话)如何使用绑定语法来表示?
我认为使用 Control.Monad
是没有解决方案,因为它内部使用 do
blocks。
我认为可以用箭头表示使用&&&
) - 也许这是一种情况,只有箭头可以用作单子的泛化?
请注意,这个问题不是关于上面的特例,而是关于计算结果在单元表达式中多次使用的一般情况,例如 print
。
是的,它们都可以转换为绑定语法;实际上,它们是由编译器内部转换的。
我希望这个例子的翻译给你提示:
main = readFilefoo.txt>> = \f - >
(print $prefix++ f)>>
(print $ f ++postfix)
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"
to
main = readFile "foo.txt" >>= print >> print "Finished"
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"
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?
I think using Control.Monad
is no solution, because it internally uses do
blocks.
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?
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
.
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")
这篇关于表达阻止只使用一元绑定语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!