63 lines
1.6 KiB
Markdown
63 lines
1.6 KiB
Markdown
# Sketch: Atomics and Mutation
|
|
|
|
What does it look like to mutate state outside of the scope of a function?
|
|
|
|
## Problem Statement
|
|
|
|
I want the ability to _modify_, _in-place_, the value of some reference or some
|
|
value on the stack. I want the ability to do this _outside_ of the scope of a
|
|
single function.
|
|
|
|
## Example Functionality
|
|
|
|
What is a `State`? How is a `state_set` implementation possible?
|
|
|
|
```
|
|
fn example: State String -> String -> IO Unit
|
|
λ state newValue => state_set state newValue
|
|
end fn
|
|
```
|
|
|
|
## Problem: Thread-Safe Access
|
|
|
|
- All access to the `State` "thing" must be thread-safe.
|
|
|
|
## Problem: Representation
|
|
|
|
- Ava, to this point, has not had any record-mutable state or the notion of such
|
|
an object.
|
|
- Ava does not and will not have inheritance (precondition).
|
|
- Must Ava have a mutable primitive?
|
|
- How could Ava support mutability without direct access? This implies that
|
|
something like `mut` as a `record` field modifier is not sufficient.
|
|
|
|
## Idea: Support via Modifiers
|
|
|
|
The following implementation is incomplete and does not enforce any thread
|
|
safety, but illustrates how `private` access could help this work.
|
|
|
|
Also, it demonstrates that anonymous function syntax needs to be considered.
|
|
|
|
```
|
|
given A
|
|
record State
|
|
private mut data: A,
|
|
end record
|
|
|
|
given A
|
|
fn state_get: State A -> IO A
|
|
λ state => defer (λ => state.data)
|
|
end fn
|
|
|
|
given A
|
|
fn state_set: State A -> A -> IO State A
|
|
λ state newValue => map (defer (λ => state.data = newValue)) (λ => state)
|
|
end fn
|
|
|
|
given A
|
|
fn state_modify: State A -> (A -> A) -> IO State A
|
|
λ state f =>
|
|
map
|
|
(defer λ => state.data = f state.data)
|
|
λ => state
|
|
```
|