Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the `do` keyword run a block or treat it as an expression?

The docs state that "The simplest way to run a block where it cannot be a stand-alone statement is by writing do before it" and provide the following example:

# This dies half of the time 
do { say "Heads I win, tails I die."; Bool.pick } or die; say "I win.";

However, do doesn't seem to cause all blocks to run. In particular, it doesn't seem to run blocks with a signature:

do -> $a = 42 { say "ran with $a"; 0 } or die; say 'done'; # OUTPUT: «done»

So would it be better to say that do treats a block as an expression which sometimes causes it to be run? Or is Rakudo incorrect in its behavior here? Or is my understanding incorrect?

like image 344
codesections Avatar asked Aug 11 '21 15:08

codesections


People also ask

Can you use the else keyword with try and except keywords?

You’ve learned that the else keyword can be used with both the if keyword and loops in Python, but it has one more use. It can be combined with the try and except Python keywords. You can use else in this way only if you also use at least one except block:

How do you use the except keyword in a block?

Notice that the except keyword can also be used in conjunction with the as keyword. This has the same effect as the other uses of as, giving the raised exception an alias so you can work with it in the except block.

What is a dodo code block?

DO executes an anonymous code block, or in other words a transient anonymous function in a procedural language. The code block is treated as though it were the body of a function with no parameters, returning void. It is parsed and executed a single time. The optional LANGUAGE clause can be written either before or after the code block.

What does the “define” block do?

The “define” block is the hat block you use to define a My Block. All blocks under the My Block definition is what runs when you run the corresponding My Block. For example -


1 Answers

Afaik:

  • Like all "statement prefixes", do consumes a "blorst" (block or statement) on its right and treats it as a statement.

  • do's only special power is that it evaluates to the value of the (last) statement. I think this is the only sense in which there's any sense of "expression" in its operation.

This interacts with the following behaviors, which are unrelated to do:

  • When a "bare" block ({...}) is treated as a statement, it runs the block.

  • Other blocks, treated as a statement, don't (or shouldn't), run.

I think the fix to the doc sentence is something like:

The simplest way to run a bare block where it cannot be is not behaving as a stand-alone statement is by writing do before it"

Though I don't know where/if the doc talks about the difference between bare blocks and other blocks.

like image 82
raiph Avatar answered Oct 12 '22 23:10

raiph