예제 #1
0
# Make sure instances are registered
import typeclasses.instances.list
import typeclasses.instances.tuple
import typeclasses.instances.function
from typeclasses.instances.maybe import Nothing, Just
from typeclasses.instances.tree import Branch, Leaf

# The function we'll map
f = lambda i: i + 1

# Instances
# =========
# fmap on lists = map to list
demo_list = [0, 1, 2, 3]
assert fmap(f, demo_list) == [1, 2, 3, 4]

# fmap on tuples = map to tuple
demo_tuple = tuple(demo_list)
assert fmap(f, demo_tuple) == (1, 2, 3, 4)

# fmap on functions = function composition
# fmap(f, g) = lambda x: f(g(x))
assert fmap(f, lambda i: i * 3)(1) == 4

# fmap on Maybe = function application on Just, Nothing on Nothing
assert fmap(f, Nothing) == Nothing
assert eq(fmap(f, Just(1)), Just(2))

# fmap on Tree = recursive fmap on branches, application on value in leafs
# I.e., if the original is
def test_args_and_kwargs():
    assert fmap(times2, ((1, 2), {'xs': [3, 4]})) == ((2, 4), {'xs': [6, 8]})
예제 #3
0
    def __str__(self):
        return 'Leaf %r' % self.value

    def __repr__(self):
        return 'Leaf %r' % self.value


class Branch(Tree):
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def __str__(self):
        return 'Branch (%r) (%r)' % (self.left, self.right)

    def __repr__(self):
        return 'Branch (%r) (%r)' % (self.left, self.right)


instance(Functor, Tree, lambda f, o: Leaf(f(o.value)) if isinstance(o, Leaf)
         else Branch(fmap(f, o.left), fmap(f, o.right)))

instance(Eq, Tree,
         lambda a, b:
             a.value == b.value if (
                 isinstance(a, Leaf) and isinstance(b, Leaf))
             else (eq(a.left, b.left) and eq(a.right, b.right)) if (
                 isinstance(a, Branch) and isinstance(b, Branch))
            else False,
         None)
def test_fmap_tuple():
    assert fmap(times2, (1, 2, 3)) == (2, 4, 6)
def test_dict_of_list():
    assert fmap(times2, {'xs': [1, 2, 3]}) == {'xs': [2, 4, 6]}
def test_fmap_range():
    assert isinstance(fmap(times2, range(3)), t.Generator)
def test_fmap_set():
    assert fmap(times2, {1, 2, 3}) == {2, 4, 6}
def test_fmap_list():
    assert fmap(times2, [1, 2, 3]) == [2, 4, 6]
def test_fmap_frozenset():
    assert fmap(times2, frozenset({1, 2, 3})) == frozenset({2, 4, 6})
def test_fmap_dict():
    assert fmap(times2, {'a': 1, 'b': 2}) == {'a': 2, 'b': 4}
def test_fmap_btes():
    assert fmap(times2, bytes([1, 2, 3])) == bytes([2, 4, 6])
def test_fmap_str():
    assert fmap(times2, 'test') == 'tteesstt'