add staticUnroll (aka static for)
#18038
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
finally gotten around to publishing a PR for this.
this is essentially D's
static foreach(https://dlang.org/spec/version.html#staticforeach), which is very useful, but more flexible, and implemented in library code.by design, it:
examples
runnableExamples: var msg = "" for T in staticUnroll([int, float]): var a: T # a is gensym'd so won't cause a redefinition error proc fn() {.gensym.} = discard # gensym needed here proc fn2(a: T): auto = a # regular overloading here msg.add $T & " " assert msg == "int float " assert fn2(1.1) == 1.1 # `staticUnroll` is evaluated in caller scope # with 2 loop parameters, the 1st one is a const int indexing the element for i, T in staticUnroll([int, float, string]): when i == 0: assert T is int elif i == 1: assert T is float else: assert T is string runnableExamples: # example showing nested loops var msg = "" proc fn1(a: auto) = msg.add $("fn1", a) proc fn2(a: auto) = msg.add $("fn1", a) for fn in staticUnroll([fn1, fn2]): for T in staticUnroll([int, float]): fn(T.default) assert msg == """("fn1", 0)("fn1", 0.0)("fn1", 0)("fn1", 0.0)""" runnableExamples: # example showing passing untyped arguments to define variables for i, name in staticUnroll([name0, name1]): const name = i assert name1 == 1note 1
I didn't name it
unrollto avoid confusion with the deprecated{.unroll.}, and which could also be revived as a library solution, but has slightly different semantics