Civet icon indicating copy to clipboard operation
Civet copied to clipboard

Declarations within `if`/`for` expressions

Open imm opened this issue 1 year ago • 1 comments
trafficstars

We can't do this (playground):

a := if cond
  tmp := x
  f(tmp)
else
  y

But we can do this (playground):

a := do if cond
  tmp := x
  f(tmp)
else
  y

We can also do this (playground)

let tmp
a := if cond
  tmp = x
  f(tmp)
else
  y

but this is lame and letconst.

Is it possible to make the first example work like the second one somehow? If the if block contains const or let, then put the body into an anonymous function, and if not, then use the current pretty compact version with the ternary operator. I understand that it is easier said than done. Personally, I can always use do before if, in such cases, since I already figured out what the catch is. But from the user's point of view, such an if does not at all seem like a ternary operator, in which it is impossible to declare a local constant or variable, especially considering the experience of other languages where this is possible.

If it would be better to leave everything as is, then perhaps it is worth at least noting this case in the reference (to say that in such cases it is just a ternary operator and nothing more). The last thought, by the way, suggests that it’s a good idea to have not only a list of what you can do in Сivet, but also what you can’t do, even if you really really want to.

imm avatar Jan 02 '24 19:01 imm

This is something we want to support eventually. I think the overall fix will be to convert the expressions to actual blocks that execute before the assignment.

Wrapping in an IIFE as a stopgap is a good start.

Related Issues: #202 #381 #888

STRd6 avatar Jan 02 '24 21:01 STRd6

I think this is resolved now. The original example gets nicely unwrapped, and even when that's not possible because the expression is inner, it gets wrapped in an IIFE.

edemaine avatar Aug 20 '24 13:08 edemaine