Civet
Civet copied to clipboard
Declarations within `if`/`for` expressions
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 let ≠ const.
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.
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
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.