Skip to content

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]

Effect that reads the current state

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]

Effect that updates the state to the result of f

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]

Effect that updates the state

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 Right wrapping a new state or a Left value wrapping an error

required

Returns:

Type Description
Try[E, None]

an Effect that updates the state if f succeeds