# ========= # 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 # # /\ # / 4 # /\ # 2 3 # # applying fmap f will yield # # /\ # / 5 # /\ # 3 4
# # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA '''Some demonstrations of the Eq typeclass and its `eq` and `ne` functions''' from typeclasses.eq import eq, ne import typeclasses.instances.list import typeclasses.instances.tuple from typeclasses.instances.maybe import Just, Nothing from typeclasses.instances.tree import Branch, Leaf # List assert eq([1, 2, 3], [1, 2, 3]) assert ne([0, 1, 2], [1, 2, 3]) # Tuple assert eq(( 1, 2, 3, ), ( 1, 2, 3, )) assert ne(( 0, 1, 2,
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)
# You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA '''Some demonstrations of the Eq typeclass and its `eq` and `ne` functions''' from typeclasses.eq import eq, ne import typeclasses.instances.list import typeclasses.instances.tuple from typeclasses.instances.maybe import Just, Nothing from typeclasses.instances.tree import Branch, Leaf # List assert eq([1, 2, 3], [1, 2, 3]) assert ne([0, 1, 2], [1, 2, 3]) # Tuple assert eq((1, 2, 3, ), (1, 2, 3, )) assert ne((0, 1, 2, ), (1, 2, 3, )) # Maybe assert eq(Nothing, Nothing) assert eq(Just(1), Just(1)) assert ne(Just(1), Just(2)) assert ne(Just(1), Nothing) # Tree assert eq(Branch(Branch(Leaf(0), Leaf(1)), Leaf(2)), Branch(Branch(Leaf(0), Leaf(1)), Leaf(2))) assert ne(Branch(Branch(Leaf(0), Leaf(1)), Leaf(2)), Branch(Branch(Leaf(0), Leaf(1)), Branch(Leaf(2), Leaf(3))))