aboutsummaryrefslogtreecommitdiff
blob: cd67fa05fd58a15830fa2422fa4cc112ce38ed1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Result type module"""

class ResultException(Exception):
    pass

class Result():
    """Result = Err E | Ok V"""

    def __init__(self, is_val):
        self._is_val = is_val

    @classmethod
    def Ok(cls, val=None):
        res = cls(True)
        res._val = val
        return res

    @classmethod
    def Err(cls, val=None):
        res = cls(False)
        res._val = val
        return res

    def is_ok(self):
        return self._is_val

    def is_err(self):
        return not self._is_val

    def ok(self):
        return self._val if self._is_val else None

    def err(self):
        return self._val if not self._is_val else None

    def map(self, f):
        return Result.Ok(f(self.ok())) if self._is_val else Result.Err(self.err())

    def map_err(self, f):
        return Result.Err(f(self.err())) if not self._is_val else Result.Ok(self.ok())

    def unwrap(self):
        return self.expect()

    def expect(self, msg='Error'):
        if self._is_val:
            return self._val
        raise ResultException(msg + ': ' + self._val)

    def unwrap_err(self):
        return self.expect_err()

    def expect_err(self, msg='Error'):
        if not self._is_val:
            return self._val
        raise ResultException(msg + ': ' + self._val)

    def __iter__(self):
        if self._is_val:
            yield self._val