Generic function

From CS 61A Wiki
Revision as of 21:11, 24 July 2014 by Axis (Talk | contribs)


Jump to: navigation, search

A generic function is a function that can operate on multiple types of data. This is especially useful when the objects we are working with have multiple representations. A good example is the variety of number representations we learned in lecture.

Techniques

The following are techniques for creating generic functions:

Interfaces

An interface manipulates different data types with the same function. For example, the + operator works with numbers, strings, and lists:

>>> 1 + 2
3
>>> 'hi ' + 'there'
'hi there'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]

Type dispatching

Type dispatching does exactly as its name suggests: depending on the type of the arguments passed in, the function will proceed in different ways. We create a function for each different combination of valid input types and then choose one to use by checking the types of arguments passed in.

For example, consider the following drive function, which takes in a variety of car types and returns the correct drive method depending on the type given:

def drive(car):
    if type(car) == SportsCar:
        return car.drive_sportscar()
    elif type(car) == Van:
        return car.drive_van()
    elif type(car) == SemiTruck:
        return car.drive_semitruck()
    elif type(car) == Tractor:
        return car.drive_tractor()

Coercion

Coercion is converting object A into object B so that A can use B's methods. This is useful when the two different objects have some similar properties and when the original object can be seen as the new type with certain modifications.

Example:

Sources