Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
960 views
in Technique[技术] by (71.8m points)

haskell - Expressing do block using only monadic bind syntax

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...