In Mathematica, one can specify the type of a module argument by giving the Head name. I am using type loosely here since Mathematica does not have types. But this does basically the same thing. So when someone calls foo
with argument which is not an integer, and foo
is defined to accept an argument whose head is integer, the call will not go through.
This is all great. But I'd like to do the same for local module variables. i.e. define a local variable that can only be assigned say Real
values or only Integer
values. But I can't do this now.
The question is, is there a way to do this?
I will give an example below how this is done in Maple, and how to do the same in Mathematica if possible. Here is a simple function that accepts only an integer. It then defines a local variable of type float
which maps to Real
in Mathematica. When it tries to assign an integer value to this variable, this is caught at run time by Maple and it gives an error. I find this feature very useful, and use it all the time, as it helps in finding errors in my code and I find it makes the code more robust.
restart;
interface(warnlevel=4);
kernelopts('assertlevel'=2):
foo:=proc(n::integer)
local m::float:=0.0;
m:=n;
end proc;
And now
foo(1)
Here is the Mathematica translation. I could only enforce the type on the arguments, but do not know how to do it for the local module variable.
ClearAll[foo]
foo[n_Integer]:=Module[{m=0.0},
m=n
]
And now
foo[1]
(*1*)
Does there exist any methods in Mathematica to do the same as in the Maple example? I understand again that Mathematica does not have types
like Maple, but may be there is other workaround to emulate this?
V 13.1 on windows
b /: HoldPattern[Set[b, Except[_Integer] ] ] := (Print["passed a non integer input"]; Abort[])
$\endgroup$q[x_] := Module[{r}, r /: HoldPattern[ Set[r, Except[_Integer] ] ] := (Print[ "passed a non integer input"]; Abort[]); r = 0.4; r ]
$\endgroup$Message
is better thanPrint
for a better looking error. One could maybe wrap that into a function like type[b,$type] $\endgroup$foo[n_Integer] := Module[{m = 0.0}, m = N[n]]
$\endgroup$