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.

64 • Chapter 3: <strong>Programming</strong> with Modules> end if> else> ’procname( args )’> end if> end proc:This not only simplifies the code used for the function case, but alsomakes it very easy to add new functions.DrawbacksUnfortunately, this implementation has serious drawbacks.• It is not extensible. The known functions are hardcoded as part ofthe procedure definition for differentiate. New functions cannotbe added without editing this source code.• A second problem relates to performance. A complete implementationwould require a table of dozens or hundreds of functions. That large tablewould need to be created and initialized each time differentiateis invoked.Encapsulation and Extensibility One way to fix both problems is tomake the table of functions a global variable. However, using global variablescan be dangerous, because they pollute the user namespace and aresubject to unwanted inspection and tampering.Solution A better solution is to put the differentiate procedure,along with its table of functions, into a module. The table is then initializedonly once–when the module is created–and can be saved to aMaple repository with the rest of the module by using a savelib call. Bymaking the table a local variable of the module, you prevent users frommodifying the table or otherwise inspecting it in unwanted ways.This does not prevent you from making the differentiator userextensible,however. You can add an access procedure addFunc that allowsusers to add rules for differentiating new functions. For example, you canuse the call> addFunc( ’cos’, x -> -sin(x) );to add the derivative of the sin function. The export addFunc of theDiffImpl module is a procedure that requires two arguments. The firstis the name of a function whose derivative is to be made known to thedifferentiator. The second is a Maple procedure of one argument thatexpresses the derivative of the function being added.

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

Saved successfully!

Ooh no, something went wrong!