Dispatch function

From CS 61A Wiki
Revision as of 14:52, 2 June 2014 by Axis (Talk | contribs)


Jump to: navigation, search

A dispatch function is a function that takes in a message and returns a relevant value.

The body of a dispatch function is always the same:

  • one conditional statement with several clauses
  • headers perform equality tests on the message

Example

def rational(x, y):
    """
    >>> rat = rational(1, 3)
    >>> rat('numer')
    1
    >>> rat('denom')
    3
    """
    def dispatch(field):
        if field == 'numer':
            return x
        elif field == 'denom':
            return y
        else:
            return 'invalid field'
    return dispatch

Sources