Tuple access by index (range)

Rescript has only one way to access tuple elements: destructuring, this limitation prevents from using them as fixed length arrays

let ageAndName = (24, "Lil' ReScript")

// possible to get item by destructuring
let (_, name) = ageAndName

// NOT ALLOWED???
let name = ageAndName[2]

Access by index it’s type safe/sound when the compiler knows the length of the array, so index it’s limited to range {0,lenght-1} even typescript knows it

imagen

The generated tuple js is a plain array so, the only thing preventing {0,lenght-1} type safe random access is the language itself

1 Like

You can do that in userspace today, but with less nice syntax and one function per tuple length.

module Tuple = {
  @get_index external get2: (('a, 'b), int) => 'a = ""
  @get_index external get3: (('a, 'b, 'c), int) => 'a = ""
  @get_index external get4: (('a, 'b, 'c, 'd), int) => 'a = ""
  @get_index external get5: (('a, 'b, 'c, 'd, 'e), int) => 'a = ""
  @get_index external get6: (('a, 'b, 'c, 'd, 'e, 'f), int) => 'a = ""
}

let myTuple = (1, "hello")

myTuple->Tuple.get2(1)->Console.log

let myTuple3 = (1, "hello", true)

myTuple3->Tuple.get3(2)->Console.log

[Playground Link]

So it would basically be just syntactic sugar, tuple length should be known at compile time as well so it seems doable.

Also, as we are on our way to get rid of the OCaml stdlib(s), we would like to get rid of fst and snd as they only support the first and second position and are of no use for larger tuples.

But at some point you should rather use a record anyways. Except maybe for special cases like React Hooks dependencies.

  1. Destructuring is sugar. The compiler uses efficient access patterns instead of actual JS destructuring.

  2. Tuples are not arrays. They are essentially records without labels, structs with a known layout. Random access is not possible. It’s the same restriction as not being able to use string keys for record fields.

1 Like

seems to be the case in Ocaml/Rescript, in contrast to other languages like ts, scala

Think of it as minimalistic anonymous structural record.

1 Like

I mean this tuple, there may be some language-specific definitions.

But again, Tuples in ReScript are not arrays. They use arrays as their target representation.

1 Like