Chris Angelico wrote:
Okay. Now let's suppose that, instead of "73" in the first step, you
have "ask the user for an integer". Are you allowed to eliminate this
prompt, since the result of it cannot possibly affect anything?

That's an excellent question. The answer is no, you're
not allowed to eliminate it, and I'll try to explain why.

In Python, you're talking about something like this:

  def get_int():
      return int(input())

  print(0 * get_int())

But you can't write it that way in Haskell, because I/O
actions are not functions that return results. The Haskell
equivalent would be something like

  main =
      get_int >>= (\n ->
          print (0 * n))

Here's what happens. We've defined 'main' as a function that
returns an I/O instruction, "get an integer". That instruction
has a callback attached, namely the lambda expression
'\n -> print (0 * n)'.

The top level of the Haskell system sees this instruction,
carries it out, and then invokes the callback, passing the
number it got as an argument.

Inside the lambda, the number is bound to n. The lambda multiplies
it by 0 and then returns *another* I/O instruction, one that says
"print this number". The Haskell system carries out that instruction.
No further I/O instructions result, so the process is terminated.

Inside the lambda, the Haskell compiler is free to notice that
n is being multiplied by 0 and optimise it to just 'print 0'.
But the body of the lambda doesn't get evaluated until *after*
the "get integer" instruction has been carried out, and there is
no evaluation path that avoids that.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to