1
|
|
|
"""Example types showing simple usage of adt.Sum.""" |
2
|
|
|
|
3
|
|
|
import typing |
4
|
|
|
|
5
|
|
|
import typing_extensions |
6
|
|
|
|
7
|
|
|
from . import adt |
8
|
|
|
from . import match |
9
|
|
|
|
10
|
|
|
# Name type variables like type variables. |
11
|
|
|
T = typing.TypeVar("T") # pylint: disable=invalid-name |
12
|
|
|
R = typing.TypeVar("R") # pylint: disable=invalid-name |
13
|
|
|
E = typing.TypeVar("E") # pylint: disable=invalid-name |
14
|
|
|
|
15
|
|
|
MaybeT = typing.TypeVar("MaybeT", bound="MaybeMixin") |
16
|
|
|
|
17
|
|
|
|
18
|
|
|
def just(pat: match.Pattern) -> match.Placeholder: |
19
|
|
|
@match.Placeholder |
20
|
|
|
def placeholder(cls: typing.Type[MaybeT]) -> MaybeT: |
21
|
|
|
return cls.Just(pat) # type: ignore |
22
|
|
|
|
23
|
|
|
return placeholder |
24
|
|
|
|
25
|
|
|
|
26
|
|
|
@match.Placeholder |
27
|
|
|
def nothing(cls: typing.Type[MaybeT]) -> MaybeT: |
28
|
|
|
return cls.Nothing() # type: ignore |
29
|
|
|
|
30
|
|
|
|
31
|
|
|
class MaybeMixin(adt.SumBase, typing.Generic[T]): |
32
|
|
|
"""Mixin that defines Maybe semantics.""" |
33
|
|
|
|
34
|
|
|
Just: adt.Ctor[T] # type: ignore |
35
|
|
|
Nothing: adt.Ctor |
36
|
|
|
|
37
|
|
|
@match.function |
38
|
|
|
def __bool__(self) -> bool: |
39
|
|
|
"""Implement coercion to bool.""" |
40
|
|
|
|
41
|
|
|
|
42
|
|
|
@MaybeMixin.__bool__.when(self=just(match.pat._)) |
43
|
|
|
def __bool_true() -> typing_extensions.Literal[True]: |
44
|
|
|
return True |
45
|
|
|
|
46
|
|
|
|
47
|
|
|
@MaybeMixin.__bool__.when(self=nothing) |
48
|
|
|
def __bool_false() -> typing_extensions.Literal[False]: |
49
|
|
|
return False |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
class Maybe(MaybeMixin, adt.Sum): # type: ignore |
53
|
|
|
"""An ADT that wraps a value, or nothing.""" |
54
|
|
|
|
55
|
|
|
|
56
|
|
|
class EitherMixin(adt.SumBase, typing.Generic[E, R]): |
57
|
|
|
"""Mixin that defines Either semantics.""" |
58
|
|
|
|
59
|
|
|
Left: adt.Ctor[E] # type: ignore |
60
|
|
|
Right: adt.Ctor[R] # type: ignore |
61
|
|
|
|
62
|
|
|
|
63
|
|
|
class Either(EitherMixin, adt.Sum): |
64
|
|
|
"""An ADT that wraps one type, or the other.""" |
65
|
|
|
|