-->

Understanding the evaluation and execution order w

2019-06-11 03:28发布

问题:

I already learned a little bit about FFL semicolons from my previous question. However, it is still not clear what order of evaluation or execution they enforce. So here is a more concrete example:

 [ expr_a, expr_b ; expr_c, expr_d ; expr_e, expr_f ]

What should be the order of execution for the above code? In my head, it should be:

  1. evaluate a & b
  2. execute a, execute b
  3. evaluate c & d
  4. execute c, execute d
  5. evaluate e & f
  6. execute e, execute f

Now let's imagine that expr_b = add(test_list, ['b saw ' + str(test_list)]) and similar for all the other expressions. Then what would be the final contents of test_list?

In my head, it should be:

a saw []

b saw []

c saw [a saw [], b saw []]

d saw [a saw [], b saw []]

e saw [a saw [], b saw [], c saw [a saw [], b saw []], d saw [a saw [], b saw []]]

f saw [a saw [], b saw [], c saw [a saw [], b saw []], d saw [a saw [], b saw []]]

Please explain why that is not the case.

回答1:

To begin with, you probably don't want to write code exactly like this. Generally, semi-colons have very low precedence, but a list literal isn't an operator, and the code will be seen like this:

[a, (b; c), (d; e), f]

This means that you are starting off four command pipelines in parallel (though two of them only have a single member). It will evaluate a, b, d, f. Then it will execute the results of a, then the results of b. Executing b will trigger the next step in the command pipeline, so it will evaluate and execute c. Then it will execute d, then evaluate and execute e, finally it will execute f.

So:

a saw []
b saw []
c saw [a saw [], b saw []]
d saw []
e saw [a saw [], b saw [], c saw [a saw [], b saw []], d saw []]
f saw []