3 ms·
I guess you could use fewer magic numbers if you want, for example instead of: proc createCRCTable(): array[256, CRC32] = for i in 0..255: You can write
by def- 12y ago
I guess you could use fewer magic numbers if you want, for example instead of:
proc createCRCTable(): array[256, CRC32] =
for i in 0..255:
You can write:
proc createCRCTable(): array[256, CRC32] =
for i in result.low .. result.high:
Or:
proc createCRCTable(): array[256, CRC32] =
for i, v in result: # index, value
Or define your own indices iterator:
iterator indices(x) =
for i in x.low .. x.high:
yield i
proc createCRCTable(): array[256, CRC32] =
for i in result.indices:
I think I should propose adding indices to the standard library.
- rogerbinns 12y agoIt isn't magic numbers as such, rather the smattering of sometimes zeroes and sometimes ones. If it was always zero or one it would be a lot less likely to have off by one errors. Python solves this by always starting from zero, and crucially not including the final number - ie range(0,3) gives 0, 1, 2 (no 3). You can also do negative indexing to count from the end - eg range(0, 3)[-1] gives the last element (2). The right thing happens when you mix the length of things into the arithmetic too - eg range(0, len(item)).
- vbit 12y agoThe 0s and 1s are specific to the examples. A range in nim `x..y` includes both x and y. Sequences are always 0-indexed. Now, if you want to start with 1 for any range you can.
- kevin_thibedeau 12y agoIt does strike me as odd that some Ada-isms are present like 'low and 'high, applicable to types and objects, but the ever useful 'range didn't get included. It is a testament to Nim's flexibility that it can be added, effectively as a one-liner. This really should be in the standard library.