7 ms·
As a pythonista one thing that struck me in the code fragments is zeroes and ones appearing everywhere. It looks very easy to have off by one errors. (It is v
by rogerbinns 12y ago
As a pythonista one thing that struck me in the code fragments is zeroes and ones appearing everywhere. It looks very easy to have off by one errors. (It is very rare to have off by one errors in Python due to the way counting and ranges work.)
- kbenson 12y agoI don't program in Python, but I thought one of the contention points the community had was the syntax of slices and such (starting at one instead of zero, or one sire of the range being inclusive, I can't recall). If that's true, I would imagine that would encourage for some off by one errors. Then again, maybe it's not nearly as contentious as it sounded in a few comments.
- def- 12y agoI 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.