wizardforcel / sicp-py-zh

:book:【译】UCB CS61a SICP Python
https://www.gitbook.com/book/wizardforcel/sicp-py/details
2.18k stars 333 forks source link

Update 2.7.md with completing missing translations #7

Closed vsxd closed 6 years ago

vsxd commented 6 years ago

There is a piece of important code and the accompanying descriptive text is not translated. This commit fixed it.

vsxd commented 6 years ago

原文中的代码,及其上下文:

Next, we use these type tags to index a dictionary that stores the different ways of adding numbers. The keys of the dictionary are tuples of type tags, and the values are type-specific addition functions.

>>> def add(z1, z2):
        types = (type_tag(z1), type_tag(z2))
        return add.implementations[types](z1, z2)

This definition of add does not have any functionality itself; it relies entirely on a dictionary called > add.implementations to implement addition. We can populate that dictionary as follows.

>>> add.implementations = {}
>>> add.implementations[('com', 'com')] = add_complex
>>> add.implementations[('com', 'rat')] = add_complex_and_rational
>>> add.implementations[('rat', 'com')] = lambda x, y: add_complex_and_rational(y, x)
>>> add.implementations[('rat', 'rat')] = add_rational

This dictionary-based approach to dispatching is additive, because add.implementations and type_tag.tags can always be extended. Any new numeric type can "install" itself into the existing system by adding new entries to these dictionaries.