11.07.2015 Views

Advanced Programming Guide

Advanced Programming Guide

Advanced Programming Guide

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

"but got %1", shape> end if;>> # Extract the "tag" information from the shape> tag := op( 0, shape );>> # Dispatch on the "tag" value> if tag = ’:-POINT’ then> Shapes:-point:-area( shape )> elif tag = ’:-SEGMENT’ then> Shapes:-segment:-area( shape )> elif tag = ’:-CIRCLE’ then> Shapes:-circle:-area( shape )> elif tag = ’:-SQUARE’ then> Shapes:-square:-area( shape )> elif tag = ’:-TRIANGLE’ then> Shapes:-triangle:-area( shape )> else> error "not a recognized shape: %1", tag> end if> end proc:3.3 Packages • 95Table-based Dispatching The third dispatch method illustrated in theShapes package is table-based. This technique is used by the exportedprocedure circumference, which references the table circum_table tolook up the appropriate routine to call. This table is built simply byassigning its entries in the body of the Shapes package.> circum_table := table();> circum_table[ ’POINT’ ] := Shapes:-point:-circumference;> circum_table[ ’SEGMENT’ ] := Shapes:-segment:-circumference;> circum_table[ ’CIRCLE’ ] := Shapes:-circle:-circumference;> circum_table[ ’SQUARE’ ] := Shapes:-square:-circumference;> circum_table[ ’TRIANGLE’ ] := Shapes:-triangle:-circumference;The source code for the procedure circumference follows.> circumference := proc( shape )> description "compute the circumference of a "> "shape expression";> if not type( shape, ’function’ ) then> error "expecting a shape, but got %1", shape> end if;> if assigned( circum_table[ op( 0, shape ) ] ) then> circum_table[ op( 0, shape ) ]( shape )> else> error "no circumference method available "> "for shape %1. Supported shapes "> "are: %2", tag,> sprintf( "%q", op( ALL_SHAPES ) )> end if> end proc:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!