Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2001

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Creating Objects

  • To: mathgroup at
  • Subject: [mg31658] Re: Creating Objects
  • From: "Ersek, Ted R" <ErsekTR at>
  • Date: Fri, 23 Nov 2001 05:46:33 -0500 (EST)
  • Sender: owner-wri-mathgroup at

Oleg Burd wanted help using the (Classes.m) package.  

While I am fluent with nearly everything in Mathematica, I have very little
experience in OOP.  So others may be able to give better answers.  Well it
appears to me that the (Classes.m) package forces one to write messy code.
Because of that and my limited background with OOP I will not try to correct
Oleg's use of (Classes.m).  However, the code below might be helpful because
it demonstrates how you can use some OOP concepts in Mathematica.

Below 'MyList' is like a class with 4 members ( 2 Strings, 1 Integer, 1 Real
I provide functions that get the Strings, Integer and Real from a MyList

   MyList[expr_]:= MatchQ[expr,{_String,_String,_Integer,_Real}]
   GetStrings[expr_?MyList]:= Take[expr,2];
   GetInt[expr_?MyList]:= Part[expr,3];
   GetReal[expr_?MyList]:= Last[expr];

    GetStrings[{ "Ted", "Ersek", 24,  9.34 }]

    { Ted,  Ersek }

Next I define 'PositiveList'  which is like a subclass of 'MyList'. 
An expression is a 'PositiveList' if it is a 'MyList' where the Integer and
Real numbers are positive. 
PositiveList effectively inherits all the features of MyList.  Next I define
a function (foo).  
When the argument of (foo) is a 'PositiveList' the product of the Integer
and Real is returned.

       MyList[expr] && Positive[GetInt[expr]] && Positive[GetReal[expr]]

    foo[expr_?PositiveList]:= GetInt[expr] * GetReal[expr]

    foo[{ "Ted", "Ersek", 24,  9.34}]


Next I demonstrate that polymorphisism is easy in Mathematica. 
Below I define a function (f) where
    f[x]= x^2  when (x is a multiple of 3)
    f[x]=x^2-1 for all other Integers
    f[x]=x  when (x) is Real

    f[ x_Integer?(Mod[#,3]===0&) ]:=  x^2;
    f[ x_Integer ]:=  x^2-1;
    f[ x_Real ]:=  x

    { f[9], f[10], f[11], f[12], f[2.3] }

   { 81, 99, 120, 144, 2.3 }

Inspite of these demonstrations I recommend that you don't try follow a
familiar paradigm (e.g. OOP) in Mathematica.  Instead you should learn
Mathematica and you will see how things should be done in Mathematica.  If
you still have concerns about code reusability, maintenance and reviews
others might be better able to further explain how those issues can be dealt
with in Mathematica. 
Ted Ersek 
Check Mathematica Tips, Tricks at

  • Prev by Date: RE: Creating Objects
  • Next by Date: Re: Log plots: plot points *linearly* equidistant
  • Previous by thread: RE: Creating Objects
  • Next by thread: Column problem