top | item 34763154

(no title)

robochat | 3 years ago

I like nim but I've never really gotten used to the slicing syntax. I guess that I'm just too used to python, plus you have to be a bit careful to leave a whitespace when doing backwards indexing so that the operators work correctly.

So python:

    a = [0,1,2,3,4,5]
    a[0:5] => [0,1,2,3,4] - half closed interval
    a[0:-1] => [0,1,2,3,4] - negative indexing
    a[:5] => [0,1,2,3,4] - skipping start index 
    a[3:] => [3,4,5] - skipping end index
nim:

    var a = [0,1,2,3,4,5]
    a[0..5] = [0,1,2,3,4,5] - closed interval
    a[0..^1] = [0,1,2,3,4,5] - closed interval with negative indexing
    a[..4] = [0,1,2,3,4] - skipping start index
    a[..<5] - Error - doesn't work
    a[3..] - Error - doesn't work
    a[0..<5] = [0,1,2,3,4] - half closed interval
    a[0..< ^1] = [0,1,2,3,4] - half closed interval with negative indexing 
                              (Important - the white space is required, it will crash otherwise!)
I'm sure that there are good reasons for this behaviour and that if you use nim a lot, you just get used to it but I find the python syntax just nicer.

discuss

order

ElegantBeef|3 years ago

To explain 'why' it behaves this way is quite simple the stdlib does not have slicing operators for all of your expected cases, Nim does not have postfix operators(aside from [], {}, *) so 3.. is just impossible to define. If one really wanted to https://play.nim-lang.org/#ix=4nSQ solves most of the issues.