I'm new to Mathematica, coming from an R and Python background, I need to use Mathematica for my thesis. I have been trying to use Return[] like I'd use return() if I needed to in R. In my practice I tried to construct a function that returns the divisors of a number x. I wrote it as follows (trying to adapt my R code from when I was learning R):
HomemadeDivisors[x_] := (a = {1}
Do[If[x/i == Quotient[x, i], a = Join[a, i], ] , {i, 2, x}]
Return[a]
)
Now I'm sure there are plenty of other things that are wrong with how I did it, but bear with me.
I try running (with expected result given below):
HomemadeDivisors[4]
> {1, 2, 4} ## Expected result
Instead I got this:
{Null Return[{Null Return[{Null Return[{If[
Mod[c If[
Mod[If[Mod[
If[{Mod[Return[2], 2], Mod[2 Return[2], 2],
Mod[3 Return[2], 2]} == 1, b[[a/2 + 0.5]],
1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c], 2] == 1,
b[[a/2 + 0.5]],
1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c], 2] == 1,
b[[a/2 + 0.5]], 1/2 (b[[a/2]] + b[[a/2 + 1]])], 2] ==
1, c = b[[a/2 + 0.5]],
c = 1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c],
2 If[Mod[
c If[Mod[
If[Mod[If[{Mod[Return[2], 2], Mod[2 Return[2], 2],
Mod[3 Return[2], 2]} == 1, b[[a/2 + 0.5]],
1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c], 2] == 1,
b[[a/2 + 0.5]],
1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c], 2] == 1,
b[[a/2 + 0.5]], 1/2 (b[[a/2]] + b[[a/2 + 1]])], 2] ==
1, c = b[[a/2 + 0.5]],
c = 1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c],
3 If[Mod[
c If[Mod[
If[Mod[If[{Mod[Return[2], 2], Mod[2 Return[2], 2],
Mod[3 Return[2], 2]} == 1, b[[a/2 + 0.5]],
1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c], 2] == 1,
b[[a/2 + 0.5]],
1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c], 2] == 1,
b[[a/2 + 0.5]], 1/2 (b[[a/2]] + b[[a/2 + 1]])], 2] ==
1, c = b[[a/2 + 0.5]],
c = 1/2 (b[[a/2]] + b[[a/2 + 1]])] Return[c]}]}]}]}
Some of this looks like code from another function I've tested unsuccessfully, but that isn't the core problem, because when I try Divisors[4] it gives me exactly the result I want without any of this garbage. So what's the problem? I'm guessing the problem is with the Return[] statement since when I rewrote another function to remove the Return[] statement the problem disappeared, but sometimes I like for the sake of my sanity to use return statements. Any guesses of what I'm doing wrong?
a = {1}
. $\endgroup$Return
"for your sanity". It does not work the way you imagine it to work (it's complicated). Mathematica is not a programming language in the sense you're trying to use it: it is an expression rewriting system. Sometimes the rewrites resemble what you get from a procedural programming language, but there are many gotchas. Look to learn Mathematica on its own terms. Trying to adapt code from another language is the path to much frustration. $\endgroup$