Difference between revisions of "Dispatch function"

From CS 61A Wiki
Jump to: navigation, search
[unchecked revision][checked revision]
(created)
 
(Examples)
 
(3 intermediate revisions by 2 users not shown)
Line 1: Line 1:
A '''dispatch function''' is a [[function]] that takes in a message and returns a relevant value.
+
{{Sufficient-class}}
 +
A '''dispatch function''' is a [[function]] that takes in a message and returns a value accordingly.
  
 
The body of a dispatch function is always the same:
 
The body of a dispatch function is always the same:
Line 5: Line 6:
 
* headers perform equality tests on the message
 
* headers perform equality tests on the message
  
== Example ==
+
== Examples ==
 +
<syntaxhighlight lang="python">
 +
def cons(a, b):
 +
  def pair(message):
 +
    if message == 'car':
 +
      return a
 +
    else:
 +
      return b
 +
  return pair
 +
 
 +
</syntaxhighlight>
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
def rational(x, y):
 
def rational(x, y):

Latest revision as of 08:21, 27 June 2014

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

The body of a dispatch function is always the same:

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

Examples

def cons(a, b):
  def pair(message):
    if message == 'car':
      return a
    else:
      return b
  return pair
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