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.

3.5 Modeling Objects • 10514 πFor instance, the expression z:-abs() is viewed as sending the absmessage to the complex number object z. The object responds by computingits absolute value.Note that each time the procedure MakeComplex is invoked, a newmodule is created using the module definition that is visible within theprocedure body. Thus, complex numbers created by different calls to theconstructor are distinct, even if the arguments real and imag are thesame. Whether a constructor should produce distinct objects for the sameinput (instance) data depends on the nature of the objects being modeled.For complex number objects, multiple calls with the same inputs shouldproduce the same object. This can be achieved by using the rememberoption in the constructor. For more information, refer to Chapter 6 of theIntroductory <strong>Programming</strong> <strong>Guide</strong>.Effect of Immutable Local States The previous MakeComplex constructorrepresents the local state of complex number objects by using two localvariables real_part and imag_part. For many object constructors, someor all of the local state of the object is expected to be immutable. In thesecases, local variables do not need to be allocated in the module to storethe local state of the object. The state can instead be represented by theparameters to the constructor, which are visible within the module by theMaple lexical scoping rules. Using this idea, the previous constructor canbe simplified as follows.> MakeComplex := proc( real, imag )> if nargs 2 then> error "real and imaginary parts are required"> end if;> module()> description "a complex number";> export re, im, abs, arg;>> re := () -> real;> im := () -> imag;> abs := () -> sqrt( real^2 + imag^2 );> arg := () -> arctan( imag, real );> end module> end proc:

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

Saved successfully!

Ooh no, something went wrong!