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.

104 • Chapter 3: <strong>Programming</strong> with Modules> if nargs 2 then> error "real and imaginary parts are required"> end if;> module()> description "a complex number";> local real_part, imag_part;> export re, im, abs, arg;>> real_part, imag_part := real, imag;> re := () -> real_part;> im := () -> imag_part;> abs := () -> sqrt( re()^2 + im()^2 );> arg := () -> arctan( im(), re() );> end module> end proc:To create the complex number 1 + i, use the constructor.> z := MakeComplex( 1, 1 );z := module()local real _part, imag_part;export re, im, abs, arg;description “a complex number”;end moduleThe procedure MakeComplex is a constructor for complex number objects.The value returned by the procedure is the instantiation of themodule whose definition appears in the body of MakeComplex.The local state of the complex number is represented by the localvariables of the module, real_part and imag_part. The behavior is representedby the exported procedures re, im, abs, and arg.The exports of a module that represents an object are sometimesviewed also as messages. Objects respond to these messages by exhibitingthe behavior that the messages elicit.> z:-re(), z:-im();1, 1> z:-abs();√2> z:-arg();

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

Saved successfully!

Ooh no, something went wrong!