Skip to content

Latest commit

 

History

History
149 lines (105 loc) · 3.2 KB

array-and-list.mdx

File metadata and controls

149 lines (105 loc) · 3.2 KB
titledescriptioncanonical
Array & List
Arrays and List data structures
/docs/manual/latest/array-and-list

Array and List

Array

Arrays are our main ordered data structure. They work the same way as JavaScript arrays: they can be randomly accessed, dynamically resized, updated, etc.

<CodeTab labels={["ReScript", "JS Output"]}>

letmyArray= ["hello", "world", "how are you"]
varmyArray=["hello","world","how are you"];

ReScript arrays' items must have the same type, i.e. homogeneous.

Usage

See the Js.Array API.

Access & update an array item like so:

<CodeTab labels={["ReScript", "JS Output"]}>

letmyArray= ["hello", "world", "how are you"] letfirstItem=myArray[0] // "hello"myArray[0] ="hey"// now ["hey", "world", "how are you"]letpushedValue=Js.Array2.push(myArray, "bye")
varmyArray=["hello","world","how are you"];varfirstItem=myArray[0];myArray[0]="hey";varpushedValue=myArray.push("bye");

List

ReScript provides a singly linked list too. Lists are:

  • immutable
  • fast at prepending items
  • fast at getting the tail
  • slow at everything else

<CodeTab labels={["ReScript", "JS Output"]}>

letmyList=list{1, 2, 3}
varmyList={hd: 1,tl: {hd: 2,tl: {hd: 3,tl: 0}}};

Like arrays, lists' items need to be of the same type.

Usage

You'd use list for its resizability, its fast prepend (adding at the head), and its fast split, all of which are immutable and relatively efficient.

Do not use list if you need to randomly access an item or insert at non-head position. Your code would end up obtuse and/or slow.

The standard lib provides a List module.

Immutable Prepend

Use the spread syntax:

<CodeTab labels={["ReScript", "JS Output"]}>

letmyList=list{1, 2, 3} letanotherList=list{0, ...myList}
varmyList={hd: 1,tl: {hd: 2,tl: {hd: 3,tl: 0}}};varanotherList={hd: 0,tl: myList};

myList didn't mutate. anotherList is now list{0, 1, 2, 3}. This is efficient (constant time, not linear). anotherList's last 3 elements are shared with myList!

Note that list{a, ...b, ...c} is a syntax error. We don't support multiple spread for a list. That'd be an accidental linear operation (O(b)), since each item of b would be one-by-one added to the head of c. You can use List.concat for this, but we highly discourage it.

Updating an arbitrary item in the middle of a list is also discouraged, since its performance and allocation overhead would be linear (O(n)).

Access

switch (described in the pattern matching section) is usually used to access list items:

<CodeTab labels={["ReScript", "JS Output"]}>

letmessage=switchmyList { | list{} =>"This list is empty" | list{a, ...rest} =>"The head of the list is the string "++Js.Int.toString(a) }
varmessage=myList ? "The head of the list is the string "+(1).toString() : "This list is empty";
close