mirror of
https://github.com/apple/pkl.git
synced 2026-01-13 15:13:38 +01:00
Local variables inside for loops yield an error #173
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @EugZol on GitHub (Jun 25, 2024).
Code:
On evaluation yields the following error:
Instead, expected to produce object with entries
2 3 4.Version:
@holzensp commented on GitHub (Jun 25, 2024):
This is a short-coming we have at the moment.
localis a modifier for a property; not a "variable." It really behaves like a property, which is why you can't have one in aforgenerator (because it's the same as generating the same property - possibly with different values - over and over).If, as in this case, you only use it in one expression, you can use
let;If you do need it in multiple places, a (admittedly sub-optimal) workaround is to use a
forgenerator again;@EugZol commented on GitHub (Jun 25, 2024):
My case was initially trying to group objects and map each subgroup under different properties of the result, but don't add the result property if the corresponding subgroup is empty. And another loop on top of that.
It went like this
Attempt 1: local variable in for-loop
Error:
Attempt 2: local variable inside leaf object
Error:
Attempt 3: instance methods
I eventually was able to solve the problem with some instance methods on Entity.
However both errors above were rather unexpected for me. Curiously, removing
whens second piece of code starts to work.@EugZol commented on GitHub (Jun 25, 2024):
I actually tried that as well! Doesn't work either, apparently because
all_enabled/all_enabledare properties as well, and that artificial for-loop would need to generate them.@holzensp commented on GitHub (Jun 25, 2024):
Works for me with that
for-as-let, becauseall_enabled/all_disabledlive inside thatnew {...}(which, btw, do you realise/intend that to beDynamic)?but also... this pattern of splitting a collection in two sub-collections based on a property is commonly called partitioning. Pkl has a
partitionmethodCollection, so I'd(I'm omitting the
whens aroundall_enabledandall_disabled, assuming that them being empty and them beingnullare equivalent; if not; you'd need to bring somewhens back)@EugZol commented on GitHub (Jun 25, 2024):
Should've tried that! I've put it inside
newbefore.That's an example. Does it matter?
That's nice! Thanks for the hint.
To summarize what I felt was inconvenient:
forrefusing to produce properties even if it is executed once: should be regular "double declaration error" insteadlocalbeing quasi-property instead of syntax sugar... maybe block form ofletstatement which could yield multiple members could be introduced insteadwhennot seeing members which are defined at the same levelHope will be addressed in the future versions!