Example #1
0
File: tree.py Project: tek/tryp.py
def path_lens_unbound_pre(a: A, sub: Callable[[A], List[A]],
                          f: Callable[[A], Maybe[Lens]], pre: Callable):
    return (
        _path_lens(pre(a), sub, f) /
        (_ / pre(lens()).add_lens) /
        __.cons(lens())
    ).smap(lens().tuple_)
Example #2
0
    def handle_input(self, input):
        '''Takes a single character string as input and alters the game
        state according to that input. Mostly, this means moving the
        player around. Returns a new game state and boolean indicating
        whether the input had an effect on the state.'''

        dirs = {
            'h': (-1, 0), 'j': (0, 1), 'k': (0, -1), 'l': (1, 0),
            'y': (-1, -1), 'u': (1, -1), 'n': (1, 1), 'b': (-1, 1),
        }

        if input in dirs:
            new_self = lens(self).player + dirs[input]
            if not new_self.player.inside():
                return self, False
            return new_self, True
        elif input == '.':
            return self, True
        elif input == 'q':
            return self.end_game(), False
        elif input == 't':
            self = lens(self).player.set(Vector.random())
            return self, True
        else:
            return self, False
Example #3
0
    def handle_input(self, input):
        '''Takes a single character string as input and alters the game
        state according to that input. Mostly, this means moving the
        player around. Returns a new game state and boolean indicating
        whether the input had an effect on the state.'''

        dirs = {
            'h': (-1, 0),
            'j': (0, 1),
            'k': (0, -1),
            'l': (1, 0),
            'y': (-1, -1),
            'u': (1, -1),
            'n': (1, 1),
            'b': (-1, 1),
        }

        if input in dirs:
            new_self = lens(self).player + dirs[input]
            if not new_self.player.inside():
                return self, False
            return new_self, True
        elif input == '.':
            return self, True
        elif input == 'q':
            return self.end_game(), False
        elif input == 't':
            self = lens(self).player.set(Vector.random())
            return self, True
        else:
            return self, False
Example #4
0
def test_type_custom_class_immutable():
    class C(object):
        def __init__(self, a):
            self._a = a

        @property
        def a(self):
            return self._a

    with pytest.raises(AttributeError):
        lens(C(9)).a.set(7)
Example #5
0
def test_type_custom_class_immutable():
    class C(object):

        def __init__(self, a):
            self._a = a

        @property
        def a(self):
            return self._a

    with pytest.raises(AttributeError):
        lens(C(9)).a.set(7)
Example #6
0
 def tuple_(self):
     x, y, z = 11, 22, 33
     def mod(a):
         a[0][1].a = B(y)
         return a[0], B(x), lens(a[2]).b.set(z)
     b = List(B(B(0)), B(B(1)), B(B(2)))
     a = A(b)
     l1 = lens().b
     l2 = lens().b[0].a
     l3 = lens().b[2]
     l = lens(a).tuple_(l1, l2, l3)
     target = A(List(B(B(x)), B(B(y)), B(B(2), z)))
     l.modify(mod).should.equal(target)
Example #7
0
    def tuple_(self):
        x, y, z = 11, 22, 33

        def mod(a):
            a[0][1].a = B(y)
            return a[0], B(x), lens(a[2]).b.set(z)

        b = List(B(B(0)), B(B(1)), B(B(2)))
        a = A(b)
        l1 = lens().b
        l2 = lens().b[0].a
        l3 = lens().b[2]
        l = lens(a).tuple_(l1, l2, l3)
        target = A(List(B(B(x)), B(B(y)), B(B(2), z)))
        l.modify(mod).should.equal(target)
Example #8
0
def test_lens_descriptor_zoom():
    class MyClass:
        def __init__(self, items):
            self._private_items = items

        def __eq__(self, other):
            return self._private_items == other._private_items

        def __repr__(self):
            return'M({!r})'.format(self._private_items)

        first = lens()._private_items[0]

    data = (MyClass([1, 2, 3]),)
    assert lens(data)[0].first_l.get() == 1
    assert lens(data)[0].first_l.set(4) == (MyClass([4, 2, 3]),)
Example #9
0
def test_lens_descriptor_zoom():
    class MyClass:
        def __init__(self, items):
            self._private_items = items

        def __eq__(self, other):
            return self._private_items == other._private_items

        def __repr__(self):
            return 'M({!r})'.format(self._private_items)

        first = lens()._private_items[0]

    data = (MyClass([1, 2, 3]), )
    assert lens(data)[0].first_l.get() == 1
    assert lens(data)[0].first_l.set(4) == (MyClass([4, 2, 3]), )
Example #10
0
File: tree.py Project: tek/tryp.py
def _path_lens(a: A, sub: Callable[[A], List[A]],
               f: Callable[[A], Maybe[Lens]]) -> Maybe[Lens]:
    def go_sub():
        l, s = sub(lens()), sub(a)
        g = lambda b: _path_lens(b, sub, f)
        return _path_lens_list(s, g) / _add(l).cons(lens())
    return (f(a) / L(List)(lens(), _)).or_else(go_sub)
Example #11
0
    class MyClass:
        def __init__(self, items):
            self._private_items = items

        def __eq__(self, other):
            return self._private_items == other._private_items

        first = lens()._private_items[0]
Example #12
0
def _path_lens(a: A, sub: Callable[[A], List[A]],
               f: Callable[[A], Maybe[Lens]]) -> Maybe[Lens]:
    def go_sub():
        l, s = sub(lens()), sub(a)
        g = lambda b: _path_lens(b, sub, f)
        return _path_lens_list(s, g) / _add(l).cons(lens())

    return (f(a) / L(List)(lens(), _)).or_else(go_sub)
Example #13
0
def test_type_custom_class_copy_and_mutate():
    class C(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b

        def __eq__(self, other):
            return self.a == other.a and self.b == other.b

    assert lens(C(C(0, 1), C(2, 3))).a.b.set(4) == C(C(0, 4), C(2, 3))
Example #14
0
 def path(self):
     c = C(1, List(C(2), C(3, List(C(4, List(C(5))), C(6))), C(7)))
     t = path_lens_pred(c, _.c, _.a, _ == 5).x
     mod = lambda a: (a + 10
                      if isinstance(a, int) else lens(a).a.modify(_ + 20))
     m = t.modify(lambda a: map(mod, a))
     target = C(21, List(C(2), C(23, List(C(24, List(C(15))), C(6))), C(7)))
     m.should.equal(target)
     m2 = t.get()
     t.set(map(mod, m2)).should.equal(target)
Example #15
0
 def path(self):
     c = C(1, List(C(2), C(3, List(C(4, List(C(5))), C(6))), C(7)))
     t = path_lens_pred(c, _.c, _.a, _ == 5).x
     mod = lambda a: (a + 10 if isinstance(a, int) else
                      lens(a).a.modify(_ + 20))
     m = t.modify(lambda a: map(mod, a))
     target = C(21, List(C(2), C(23, List(C(24, List(C(15))), C(6))), C(7)))
     m.should.equal(target)
     m2 = t.get()
     t.set(map(mod, m2)).should.equal(target)
Example #16
0
def test_type_custom_class_copy_and_mutate():
    class C(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b

        def __eq__(self, other):
            return self.a == other.a and self.b == other.b

    assert lens(C(C(0, 1), C(2, 3))).a.b.set(4) == C(C(0, 4), C(2, 3))
Example #17
0
    class MyClass:
        def __init__(self, items):
            self._private_items = items

        def __eq__(self, other):
            return self._private_items == other._private_items

        def __repr__(self):
            return 'M({!r})'.format(self._private_items)

        first = lens()._private_items[0]
Example #18
0
    def advance_robots(self):
        '''Produces a new game state in which the robots have advanced
        towards the player by one step. Handles the robots crashing into
        one another too.'''

        new_robots = set()
        crashes = set(self.crashes)
        for old_pos in self.robots:
            new_pos = old_pos.step_towards(self.player)
            if new_pos in new_robots:
                crashes.add(new_pos)
                new_robots.remove(new_pos)
            elif new_pos in crashes:
                pass
            else:
                new_robots.add(new_pos)

        return lens(self).tuple_(
            lens().robots,
            lens().crashes,
        ).set((new_robots, crashes))
Example #19
0
    def advance_robots(self):
        '''Produces a new game state in which the robots have advanced
        towards the player by one step. Handles the robots crashing into
        one another too.'''

        new_robots = set()
        crashes = set(self.crashes)
        for old_pos in self.robots:
            new_pos = old_pos.step_towards(self.player)
            if new_pos in new_robots:
                crashes.add(new_pos)
                new_robots.remove(new_pos)
            elif new_pos in crashes:
                pass
            else:
                new_robots.add(new_pos)

        return lens(self).tuple_(
            lens().robots,
            lens().crashes,
        ).set((new_robots, crashes))
Example #20
0
def test_type_custom_class_lens_setattr():
    class C(object):
        def __init__(self, a):
            self._a = a

        @property
        def a(self):
            return self._a

        def __eq__(self, other):
            return self.a == other.a

        def _lens_setattr(self, key, value):
            if key == 'a':
                return C(value)

    assert lens(C(C(9))).a.a.set(4) == C(C(4))
Example #21
0
def test_type_custom_class_method_lens_setter():
    class C(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b

        def __eq__(self, other):
            return self.a == other.a and self.b == other.b

        def lens_setter(self, kind, key, value):
            if kind == 'setattr':
                if key == 'a':
                    return C(value, self.b)
                elif key == 'b':
                    return C(self.a, value)

    assert lens(C(C(0, 1), C(2, 3))).a.b.set(4) == C(C(0, 4), C(2, 3))
Example #22
0
def test_type_custom_class_lens_setattr():
    class C(object):

        def __init__(self, a):
            self._a = a

        @property
        def a(self):
            return self._a

        def __eq__(self, other):
            return self.a == other.a

        def _lens_setattr(self, key, value):
            if key == 'a':
                return C(value)

    assert lens(C(C(9))).a.a.set(4) == C(C(4))
Example #23
0
File: tree.py Project: tek/tryp.py
def path_lens_unbound(a: A, sub: Callable[[A], List[A]],
                      f: Callable[[A], Maybe[Lens]]) -> Maybe[Lens]:
    return _path_lens(a, sub, f).smap(lens().tuple_)
Example #24
0
def test_lens_no_double_bind():
    with pytest.raises(ValueError):
        lens(1).bind(2)
Example #25
0
File: tree.py Project: tek/tryp.py
def path_lens_pred(a: A, sub: Callable[[A], List[A]], lsub,
                   f: Callable[[A], bool]):
    g = lambda a: Boolean(f(lsub(a))).maybe(lsub(lens()))
    return path_lens(a, sub, g)
Example #26
0
def test_lens_no_double_bind():
    with pytest.raises(ValueError):
        lens(1).bind(2)
Example #27
0
def test_lens_flip():
    l = lens().iso_(str, int).flip()
    assert l.bind('1').get() == 1
Example #28
0
def test_lens_add_lens_bad_lens():
    with pytest.raises(TypeError):
        lens([1, 2]).add_lens(1)
Example #29
0
def test_lens_bind():
    assert lens().bind([1, 2, 3]).get() == [1, 2, 3]
Example #30
0
def test_ZoomLens_get():
    l = b.GetitemLens(0) & b.ZoomLens()
    data = [lens([1, 2, 3])[1]]
    assert l.get(data) == 2
Example #31
0
    def end_game(self, message=''):
        '''Returns a completed game state object, setting an optional
        message to display after the game is over.'''

        self = lens(self).message.set(message)
        return lens(self).running.set(False)
Example #32
0
def test_lens_add_lens_nontrivial_lens():
    assert lens([1, 2]).add_lens(lens()[1]).set(3) == [1, 3]
Example #33
0
 def mod(a):
     a[0][1].a = B(y)
     return a[0], B(x), lens(a[2]).b.set(z)
Example #34
0
def test_lens_add_lens_bad_lens():
    with pytest.raises(TypeError):
        lens([1, 2]).add_lens(1)
Example #35
0
def test_lens_add_lens_bound_lens():
    with pytest.raises(ValueError):
        lens([1, 2]).add_lens(lens(1))
Example #36
0
 def lens(self, fa: F[A], f: Callable[[A], bool]) -> Maybe[Lens]:
     return self.index_where(fa, f) / (lambda i: lens()[i])
Example #37
0
 def find_lens_pred(self, fa: F[A], f: Callable[[A], bool]) -> Maybe[Lens]:
     g = lambda a: Boolean(f(a)).maybe(lens())
     return self.find_lens(fa, g)
Example #38
0
def test_TupleLens_set_with_Lens():
    data = {'hello': 0, 'world': 1}
    my_lens = b.TupleLens(lens()['hello'], lens()['world'])
    assert my_lens.set(data, (3, 4)) == {'hello': 3, 'world': 4}
Example #39
0
def test_lens_add_lens_bound_lens():
    with pytest.raises(ValueError):
        lens([1, 2]).add_lens(lens(1))
Example #40
0
def test_ZoomLens_get():
    l = b.GetitemLens(0) & b.ZoomLens()
    data = [lens([1, 2, 3])[1]]
    assert l.get(data) == 2
Example #41
0
def test_lens_get():
    assert lens(10).get() == 10
    assert lens([1, 2, 3])[1].get() == 2
Example #42
0
def test_ZoomLens_set():
    l = b.GetitemLens(0) & b.ZoomLens()
    data = [lens([1, 2, 3])[1]]
    assert l.set(data, 7) == [[1, 7, 3]]
Example #43
0
def test_lens_no_bind():
    with pytest.raises(ValueError):
        lens().get()
Example #44
0
File: tree.py Project: tek/tryp.py
 def go_sub():
     l, s = sub(lens()), sub(a)
     g = lambda b: _path_lens(b, sub, f)
     return _path_lens_list(s, g) / _add(l).cons(lens())
Example #45
0
def test_lens_flip():
    l = lens().iso_(str, int).flip()
    assert l.bind('1').get() == 1
Example #46
0
def test_TupleLens_get_with_Lens():
    data = {'hello': 0, 'world': 1}
    my_lens = b.TupleLens(lens()['hello'], lens()['world'])
    assert my_lens.get(data) == (0, 1)
Example #47
0
 def mod(a):
     a[0][1].a = B(y)
     return a[0], B(x), lens(a[2]).b.set(z)
Example #48
0
def test_lens_bind():
    assert lens().bind([1, 2, 3]).get() == [1, 2, 3]
Example #49
0
File: tree.py Project: tek/tryp.py
from typing import TypeVar, Callable

from lenses import Lens, lens

from tryp import Maybe, List, __, Boolean, _, L

A = TypeVar('A')

_add = lambda l: __.map(lens().add_lens(l).add_lens)


def path_lens_pred(a: A, sub: Callable[[A], List[A]], lsub,
                   f: Callable[[A], bool]):
    g = lambda a: Boolean(f(lsub(a))).maybe(lsub(lens()))
    return path_lens(a, sub, g)


def path_lens(a: A, sub: Callable[[A], List[A]],
              f: Callable[[A], Maybe[Lens]]) -> Maybe[Lens]:
    return _path_lens(a, sub, f).smap(lens(a).tuple_)


def path_lens_unbound_pre(a: A, sub: Callable[[A], List[A]],
                          f: Callable[[A], Maybe[Lens]], pre: Callable):
    return (
        _path_lens(pre(a), sub, f) /
        (_ / pre(lens()).add_lens) /
        __.cons(lens())
    ).smap(lens().tuple_)

Example #50
0
def test_lens_add_lens_trivial_lens():
    assert lens([1, 2]).add_lens(lens()) + [3] == [1, 2, 3]
Example #51
0
def test_lens_no_bind():
    with pytest.raises(ValueError):
        lens().get()
Example #52
0
def test_lens_add_lens_nontrivial_lens():
    assert lens([1, 2]).add_lens(lens()[1]).set(3) == [1, 3]
Example #53
0
def test_lens_add_lens_trivial_lens():
    assert lens([1, 2]).add_lens(lens()) + [3] == [1, 2, 3]
Example #54
0
 def find_lens(self, fa: F[A], f: Callable[[A], Maybe[Lens]]) -> Maybe[Lens]:
     check = lambda a: f(a[1]) / (lambda b: (a[0], b))
     index = lambda i, l: lens()[i].add_lens(l)
     wi = self.with_index(fa)
     return self.find_map(wi, check).map2(index)
Example #55
0
File: tree.py Project: tek/tryp.py
def _path_lens_list(fa: List[A], f: Callable[[A], Maybe[Lens]]) -> Maybe[Lens]:
    check = lambda a: f(a[1]) / (lambda b: (a[0], b))
    cat = lambda i, l: _add(lens()[i])(l)
    return fa.with_index.find_map(check).map2(cat)
Example #56
0
def test_lens_add_lens_nontrivial_LensLike():
    assert lens([1, 2]).add_lens(baselens.GetitemLens(1)).set(3) == [1, 3]
Example #57
0
def test_TupleLens_set_with_Lens():
    data = {'hello': 0, 'world': 1}
    my_lens = b.TupleLens(lens()['hello'], lens()['world'])
    assert my_lens.set(data, (3, 4)) == {'hello': 3, 'world': 4}
Example #58
0
def test_lens_get():
    assert lens(10).get() == 10
    assert lens([1, 2, 3])[1].get() == 2
Example #59
0
def test_ZoomLens_set():
    l = b.GetitemLens(0) & b.ZoomLens()
    data = [lens([1, 2, 3])[1]]
    assert l.set(data, 7) == [[1, 7, 3]]
Example #60
0
def test_TupleLens_get_with_Lens():
    data = {'hello': 0, 'world': 1}
    my_lens = b.TupleLens(lens()['hello'], lens()['world'])
    assert my_lens.get(data) == (0, 1)