Hello,
sometimes in C++ I write something like this to avoid extra indentation levels:
for(int i = 0; i < 10; i++) if(cond(i))
{
doSomething();
...
}
When I do the same thing in Nim, I get "Error: nestable statement requires indentation".
I can write something line this:
for i in 0..<10: (if cond(i):
doSomething()
)
but I would like to get rid of those parentheses, it's like going back to curly braces syntax.
I ended up writing a forif macro. But then I would have to write a macro for every combo. Is there a better way to do this?
short answer no.
This is the parsing tradeoff between curlies and indentation syntax.
There are more functional syntaxes available, that you might like, e.g.
import zero_functional
for i in 0..10:
if i mod 2==0:
echo i
0..10 --> filter(it mod 2 == 0) --> foreach(echo it)
I'd like to add that most chains you get with zero_functional are still iterators, so you can use it this way:
import zero_functional
for i in 0..<10 --> filter(it mod 2 == 0).map(it * 2):
echo i
With recent changes to the compiler one can do a slight hack of making template/macros that take a iterable. We can do 0 cost iteration functions like so https://github.com/beef331/slicerator/blob/itermacros/src/itermacros.nim#L45-L115
So in the example used here it's as simple as
for i in filterit(0..<10, it mod 2 == 0).mapIt(it * 2):
echo i