I want to make and use object like stuff of Object-Oriented Programming language(like JavaScript) in Mathematica and am trying it by referring to the answer of this question using Module
.
For example, I want to make an object(Module) which has the following properties and Methods:
Properties:
- a : 2 (integer)
- b : 4^a
- f : func[a], with
func: function which just returns an argument doing nothing else. (func : x -> x)
- c = 4^f
Methods:
- showA: returns a
- showB: returns b
- showC: returns c
I wrote a code below, but the result was not what I had expected:
In[529]:= func[x_] := (
Return[x]
)
foo = Module[
{
a = 2,
b = 4^a,
f = func[a],
c = 4^f
},
Switch[#,
"showA", a,
"showB", b,
"showC", c
]
&];
foo["showA"]
foo["showB"]
foo["showC"]
Out[531]= 2
Out[532]= 1048576 //expected output: 16
Out[533]= 4^f //expected output :16
What is wrong? If it is impossible to do, what is the alternative simplest way to achieve this?
Any information would be appreciated.
Module[{a = 3, b = 4 a}, f[a,b]]
would givef[3, 4a]
, because thea
on the rhs ofb = 4 a
is not the "module version" ofa
, but the externala
. (You can notice this from the syntax highlighting—it's blue, not green.) $\endgroup$func[x_] := (Return[x])
means what you might think it means!Return
is only used for control flow changes in mathematica, like breaking out ofFor
loops or sequential evaluation (;
). You'll still get the expected output fromfunc
in this case, but you may as well usefunc[x_] := x
. $\endgroup$Return
instead of writingfunc[x_] := x
is just I wanted to know whether it works as a "return" keyword of other ordinary programming languages. The function I need in my actual project requires much more to do thanfunc[x_] := x
(including For loop calculation) and I thought I needed to useReturn
for returning the result. $\endgroup$