17

I'm just learning Haskell and IO monads. I'm wondering why wouldn't this force the program to output "hi" as well as "bye":

second a b = b
main = print ((second $! ((print "hi") >>= (\r -> return ()))) "bye")

As far as I understand, the $! operator would force the first argument of second to be evaluated, and the >>= operator would need to run print "hi" in order to get a value off of it and pass it to \r -> return (), which would print "hi" to the screen.

What's wrong with my reasoning?

And also, is there any way to proove Haskell cannot be tricked (other than using unsafe functions) into running IO operations inside "safe" code?

Juan
  • 15,274
  • 23
  • 105
  • 187
  • 6
    BTW, your code can be simplified to `main = print (print "hi" \`seq\` "bye")` – Joachim Breitner Jul 16 '14 at 08:52
  • 7
    Answer: Because you can't trick Haskell. – Don Stewart Jul 17 '14 at 07:04
  • As noted by Joachim, `($!)` make use of `seq`, which has caught out many a developer e.g. see [GHC issue #5129](https://gitlab.haskell.org/ghc/ghc/-/issues/5129) for another problematic use of `seq` which is raised by [ezyang](http://blog.ezyang.com/about); it provides more details as to why your code example won't work in Haskell 2010. – atravers Jul 27 '20 at 12:53

2 Answers2

34

The expression you are forcing is ((print "hi") >>= (\r -> return ())), which is of type IO (). As such it represents an IO action. But evaluating such a thing is quite different from running it!

Evaluating a value means performing just enough steps to turn it into what is called weak head normal form. Because IO is abstract, it is a bit tricky to see what that means in this case, but one can think of IO a as RealWorld -> (a, RealWorld), and then the weak head normal form is, well, a function waiting to be given the RealWorld.

Running implies evaluation, but also passes the RealWorld as an argument, thus causing the IO effect to happen.

All this is not very specific to IO; your confusion and the concepts apply equally to a -> b. If you understand what $! does when the second argument is a function, you’ll understand what happens when it is an IO action.

Community
  • 1
  • 1
Joachim Breitner
  • 25,395
  • 6
  • 78
  • 139
21

You're confusing evaluation with execution. When you force an expression like print "hi", that doesn't print anything out. It just produces a value (in this case, a value of type IO()) representing the action of printing something out. You can think of the value of print "hi" as a recipe for printing "hi".

dfeuer
  • 48,079
  • 5
  • 63
  • 167