box¶
Class for a stateful container that can hold at most one item.
- class pythonic_fp.gadgets.box.Box¶
- class pythonic_fp.gadgets.box.Box(item: T)
Container holding at most one item of a given type.
Note
Box(item: T): contains at one item of typeTBox[T](): creates empty container
Where type
Tis some definite type, which could beNoneor evenNever.Tip
Boxobjects can be used in Python match statements.- Parameters:
item – An “optional” initial contained
itemfor theBox.
- bind(f: Callable[[T], Box]) Box¶
Flatmap
Boxwith functionf.- Parameters:
f – binding function
- Returns:
a new instance
- exchange(new_item: T) T¶
Exchange an item with what is in the Box.
- Parameters:
new_item – New item to exchange for current item.
- Returns:
Original contents of the
Box.- Raises:
ValueError – If Box is empty.
- get() T¶
- get(alt: T) T
Return the contained item if it exists, otherwise an alternate item.
- Parameters:
alt – an “optional” item of type
Tto return ifBoxis empty- Returns:
contents of
Box, or an alternate item if given andBoxempty- Raises:
ValueError – when an
altitem is not provided but needed
- map(f: Callable[[T], U]) Box¶
Map function
fover contents. We need to return a new instance since the type of Box can change.- Parameters:
f – mapping function
- Returns:
a new instance
- pop() T¶
Pop the contained item if
Boxis not empty.- Returns:
The item contained in the
Box.- Raises:
ValueError – If Box is empty.
- push(item: T) None¶
Push an item into an empty
Box.- Parameters:
item – Item to push into the empty
Box.- Raises:
ValueError – If
Boxis not empty.
- put(item: T) None¶
Put an item in the Box. Discard any previous contents.