Draco-lang / Language-suggestions

Collecting ideas for a new .NET language that could replace C#
75 stars 5 forks source link

Python like negative indexing #62

Open Binto86 opened 2 years ago

Binto86 commented 2 years ago

Introduction

It would be nice to have nagative indexing like in python

Example

this is how it could work in Fresh

int lastItem=foo[-1]; //returns last item of the array
int secondToLast=foo[-2]; //second to last item

this code would be equivalent to this in c#

int lastItem=foo[foo.Lenght-1]; //returns last item of the array
int secondToLast=foo[foo.Lenght-2]; //second to last item

Use Case

While working with algorithms you often need to get the last item of the array and typing foo.Lenght-1 every time you need to get the item is very annoying. This functionality would be very nice to have.

WhiteBlackGoose commented 2 years ago

Hi. Have you seen C#'s Ranges and Indices? It seems to be doing the job quite well

One problem with this suggestion is that whilst we could interpret -1 as a literal for thisArray.Length-1. But what if you used an expression for index, which turned out to be negative? Arrays come from .NET's BCL, which will throw an out of range exception

Binto86 commented 2 years ago

Hi. Have you seen C#'s Ranges and Indices? It seems to be doing the job quite well

i didnt know about that, but it seems like it would be mess with binary XOR

But what if you used an expression for index, which turned out to be negative? Arrays come from .NET's BCL, which will throw an out of range exception

well there is messy solution just calculate the expresion and if it is negative add foo.Length before it i know that would be very bad solution, but there probably is some resonable solution

Kuinox commented 10 months ago

As @WhiteBlackGoose said, I too don't like negative indexing because it make an accidental out of bound access valid.
I prefer the C# Range thing, even if I don't really like the cryptic syntax