Skip to content

pfun.ref.Ref dataclass

Wraps a value that can be mutated as an Effect

__init__(self, value) special

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:

1
2
3
>>> ref = Ref('the state')
>>> ref.get().run(None)
'the state'

Returns:

Type Description
pfun.effect.Effect[object, NoReturn, ~A]

Effect that reads the current state

modify(self, f)

Modify the value wrapped by this Ref by applying f in isolation

Examples:

1
2
3
4
5
>>> ref = Ref([])
>>> ref.modify(lambda l: l + [1]).run(None)
None
>>> ref.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
pfun.effect.Effect[object, NoReturn, NoneType]

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:

1
2
3
4
5
>>> ref = Ref('initial state')
>>> ref.put('new state').run(None)
None
>>> ref.value
'new state'

Parameters:

Name Type Description Default
value ~A

new state

required

Returns:

Type Description
pfun.effect.Effect[object, NoReturn, NoneType]

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> from pfun.either import Left, Right
>>> ref = Ref('initial state')
>>> ref.try_modify(lambda _: Left('Whoops!')).either().run(None)
Left('Whoops!')
>>> ref.value
'initial state'
>>> ref.try_modify(lambda _: Right('new state')).run(None)
None
>>> ref.value
'new state'

Parameters:

Name Type Description Default
f Callable[[~A], Union[pfun.either.Left[~E], pfun.either.Right[~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
pfun.effect.Effect[object, ~E, NoneType]

an Effect that updates the state if f succeeds