pfun.state.State
dataclass
Wraps a value that can be mutated as an Effect
__init__(self, value)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
A |
The initial state |
required |
get(self)
Get an Effect
that reads the current state of the value
Examples:
>>> state = State('the state')
>>> state.get().run(None)
'the state'
Returns:
Type | Description |
---|---|
Success[A] |
|
modify(self, f)
Modify the value wrapped by this State
by applying f
in isolation
Examples:
>>> state = State([])
>>> state.modify(lambda l: l + [1]).run(None)
None
>>> state.value
[1]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
f |
Callable[[A], A] |
function that accepts the current state and returns a new state |
required |
Returns:
Type | Description |
---|---|
Success[None] |
|
put(self, value)
Get an Effect
that updates the current state of the value
Examples:
>>> state = State('initial state')
>>> state.put('new state').run(None)
None
>>> state.value
'new state'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
A |
new state |
required |
Returns:
Type | Description |
---|---|
Success[None] |
|
try_modify(self, f)
Try to update the current state with the result of f
if it succeeds.
The state is updated if f
returns a Right
value, and kept
as is otherwise
Examples:
>>> from pfun.either import Left, Right
>>> state = State('initial state')
>>> state.try_modify(lambda _: Left('Whoops!')).either().run(None)
Left('Whoops!')
>>> state.value
'initial state'
>>> state.try_modify(lambda _: Right('new state')).run(None)
None
>>> state.value
'new state'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
f |
Callable[[A], Either[E, A]] |
function that accepts the current state and returns a |
required |
Returns:
Type | Description |
---|---|
Try[E, None] |
an |