Create an array of custom type

Hello, I am new to the language, and sadly, I could not find an example of this kind of process in documentation!

so let say I have codes like

type a = {
    x: int,
    y: int
}

let arr = [ [1,2], [3,4], [5,6], [7,8] ]

How can I create an array of type ‘a’ using datas of ‘arr’?

You defined “a” as a record so what you would need is:
let arr = [{x: 1, y: 2}, {x: 3, y: 4}, {x: 5, y: 6}, {x: 7, y: 8}]
The type annotation for arr would be array<a>

1 Like

You can ‘map’ the array arr to a new array using https://rescript-lang.org/docs/manual/latest/api/belt/array#map

Pass it a function which takes the individual element arrays and returns a value of the record type a.

Btw, let arr = [ [1,2], [3,4, ... ] to create an array of pairs is not really the correct way in ReScript. It’s more of a JavaScript/TypeScript idiom. In ReScript you would use tuples: let arr = [(1, 2), (3, 4), ...]. Tuples have a fixed length so you can ensure that all the elements are pairs.

2 Likes

I am not sure I understand it well,

so if I declare type, then after that, all the variables with same structures (in this case {x, y}) define as the type?

I’m quite confused with struct in C/C++, what are the difference between struct in C/C++ and type in Rescript?

Good explanations in the docs: https://rescript-lang.org/docs/manual/latest/record

1 Like