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 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/guide/lists.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ let oneTwoThree = [1, ...twoThree]
print(oneTwoThree) // [1, 2, 3]
```

## 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 implemented as singly-linked lists, and therefore prepending new elements to the beginning of one is a very efficient operation (the last new element could then simply point 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, the entire list being spread will have to be copied one element at a time in order to create the new list while also not mutating the old list.
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