length's type.

Gary Chike chikega at gmail.com
Fri Feb 9 02:13:04 UTC 2024


On Thursday, 8 February 2024 at 16:54:36 UTC, Kevin Bailey wrote:

> Additionally, it doesn't address the issue. It still requires 
> me to both realize the issue with comparing an int to length's 
> mystery type, as well as to fix it for the compiler.
>
> (And it's beside the fact that the start value could just as 
> easily be an int (parameter for example) that could take a 
> negative value. This was the case for one of my cases.)

It appears that some strongly typed languages like Rust 
necessitate explicit casting similar to D in this particular 
case. And some extremely strongly typed languages like Ada 
requires it to another level.

```rust

fn main() {
     let something = vec!['a', 'b', 'c'];

     println!("len: {}", something.len()); // 3

     for i in -1..=something.len() as i32 {
         println!("i: {}", i);
     }
}
```
Like D, Rust's 'len()' function returns an unsigned integer 
`usize`. It has to be cast to `int` to deal with the `-1` index 
or it will not compile.
```
  for i in -1..=something.len() {
   |              ^^ the trait `Neg` is not implemented for `usize`
```

But there are some modern languages in which the length function 
returns a signed integer by default .. such as Odin. [`len :: 
proc(v: Array_Type) -> int 
{…}`](https://pkg.odin-lang.org/base/builtin/#len). So there is 
no requirement for casting in Odin in this particular case. An 
experienced Odin programmer replied to me on the Odin Discord 
stated: "It is int in the default context, but if the type system 
sees it is being used in the context of something that wants a 
uint it will return that."

```c
package main

import "core:fmt"

main :: proc() {
     something := []byte{'a', 'b', 'c'}

     fmt.println("length of 'len(something): ", len(something))
     fmt.printf("type of 'len(something)': %T\n", len(something))  
// int
     for i := -1; i < len(something); i += 1 {
         fmt.println("i: ", i)
     }
}
```
Thank you everyone for this interesting discussion on languages 
and language design.



More information about the Digitalmars-d-learn mailing list