Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Document arbitrary-position list spreads #346

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/guide/lists.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ let numbers = [1, 2, 3]
let strings = ["foo", "bar", "baz"]
```

Lists in Grain are linked lists, so if we'd like to add a new item to a list, we add it to the front:
Lists in Grain are linked lists, so if we'd like to add a new item to a list, the preferred way is to add it to the front, which we can do with the spread syntax (`...`):
alex-snezhko marked this conversation as resolved.
Show resolved Hide resolved

```grain
let twoThree = [2, 3]
Expand All @@ -23,6 +23,18 @@ let oneTwoThree = [1, ...twoThree]
print(oneTwoThree) // [1, 2, 3]
```

For convenience, it is also possible to use the spread syntax at any position in a list:

```grain
let oneTwo = [1, 2]
let threeFour = [3, 4]
let result = [...oneTwo, ...threeFour, 5]

print(result) // [1, 2, 3, 4, 5]
```

However, it is important to be aware of the **performance implications of arbitrary-position spreads**: in general, including a single spread at the end of a list expression is much more efficient than including a spread anywhere else as the latter requires copying the entire list(s) being spread.
alex-snezhko marked this conversation as resolved.
Show resolved Hide resolved

alex-snezhko marked this conversation as resolved.
Show resolved Hide resolved
We can also write functions that process data in lists, but we'll save that fun for the section on Pattern Matching.

## The List Standard Library
Expand Down