Skip to content

feat: Document arbitrary-position list spreads #346

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
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
16 changes: 16 additions & 0 deletions src/guide/lists.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@ print(oneTwoThree) // [1, 2, 3]

We can also write functions that process data in lists, but we'll save that fun for the section on Pattern Matching.

## More On Spreads (`...`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
## More On Spreads (`...`)
## More on Spreads (`...`)


Although spreads are recommended to only be put at the end of a list, 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**. Grain lists are immutable linked lists, and therefore prepending new elements to the beginning of one is a very efficient operation—the new element simply points to the list being extended! On the other hand, we do not get this same benefit if a spread appears somewhere other than at the end of a list expression. In this case, a brand new list must be created, copying one element at a time, pointing each one at the next, to point to the new elements at the end.

Use arbitrary-position spreads sparingly, only when they make your code more expressive and where performance isn't a major concern.

## The List Standard Library

Lists wouldn't be all that interesting if we couldn't do anything with them, right? Conveniently, the Grain standard library provides a set of functions that work with lists.
Expand Down