11.07.2015 Views

Advanced Programming Guide

Advanced Programming Guide

Advanced Programming Guide

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

60 • Chapter 3: <strong>Programming</strong> with ModulesThe following example shows several steps in the development of themodule, from a very simple first try to the final, fully functional program.The final form of the differentiator is a good illustration of a very commonMaple design pattern. This pattern arises when you have a single top-levelroutine that dispatches a number of subroutines to handle special casesusing special purpose algorithms.The First Attempt This initial example presents the differentiator asan ordinary procedure, not a module.> differentiate := proc( expr, var )> local a, b;>> if type( expr, ’constant’ ) then> 0> elif expr = var then> 1> elif type( expr, ’‘+‘’ ) then> map( procname, args )> elif type( expr, ’‘^‘’ ) then> a, b := op( expr );> if a = var and not has( b, var ) then> b * a ^ ( b - 1 )> else> ’procname( args )’> end if> elif type( expr, ’‘*‘’ ) then> a, b := op( 1, expr ), subsop( 1 = 1, expr );> procname( a, var ) * b + a * procname( b, var )> else> ’procname( args )’> end if> end proc:Trivial cases are handled first: The derivative of a constant expression isequal to 0, and the derivative of the variable with respect to which we aredifferentiating is equal to 1. The additivity of the derivative operator isexpressed by mapping the procedure over sums, using the command> map( procname, args );This is commonly used to map a procedure over its first argument,passing along all the remaining arguments. Only the simple case of powersof the differentiation variable is handled so far, provided also that thepower is independent of the differentiation variable. The product rule forderivatives is expressed by splitting expressions of type product into twopieces:• the first factor in the product, and• the product of all the remaining factors.

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

Saved successfully!

Ooh no, something went wrong!