Civet icon indicating copy to clipboard operation
Civet copied to clipboard

`for`/`else`

Open bbrk24 opened this issue 1 year ago • 4 comments

From Python. Real-world situation where I want it:

        fail .= false
        for i .= engine.board.tableau[src.1 as number]# - 1; i >= src.2!; --i
          unless engine.moveTableauToFoundation src.1 as number, dest.1 as 'asc' | 'desc', dest.2 as number
            fail = true
            break
        if fail
          // May have made partial progress; restore from history
          engine = Engine.fromJSON history.-1
        else
          unHighlight()
          updateRender()

vs with for/else:

        for i .= engine.board.tableau[src.1 as number]# - 1; i >= src.2!; --i
          unless engine.moveTableauToFoundation src.1 as number, dest.1 as 'asc' | 'desc', dest.2 as number
            // May have made partial progress; restore from history
            engine = Engine.fromJSON history.-1
            break
        else
          unHighlight()
          updateRender()

bbrk24 avatar May 15 '24 01:05 bbrk24

We discussed this at some length here: #1083 (and probably Discord before that) Ha, there's even an ancient partial PR for it: #359

While I agree for..else is intuitive if you come from Python, Daniel pointed out that it's ambiguous whether else is the break case or the non-break case. Both are common, depending on the use-case. (Does break mean "I succeeded" or "I failed"?) The idea was to allow both options, via if break or unless break (and else clauses). I feel like things then got a little more complicated with assigning to break and if break? and I'm not sure we ended up in the best proposal... but perhaps we can refine it to find the best form.

edemaine avatar May 15 '24 02:05 edemaine

Some relevant Python references:

  • https://stackoverflow.com/a/23748240/68210
  • https://youtu.be/OSGv2VnC0go?t=950

I'm a fan of the capability but I'd like to find a better way to name it. The Python for ... else way seems to be confusing even for Python fans. It would also be nice to have a clause for the break path as well, similar to how we have try ... catch ... else ....

STRd6 avatar May 15 '24 02:05 STRd6

I think another interesting ambiguity, and one that arises in certain situations, perhaps during debugging if nowhere else, is whether the loop ran at all. If the body of the loop body didn't run then else block is executed, otherwise else block is not executed.

This is a natural and perhaps useful way to think of an else block, as it mirrors the if else statement.

wmstack avatar Oct 24 '24 16:10 wmstack