This is the code in Mathematica:

h[x_] := (If[x > 5, Return[big]]; t = x^3; Return[t - 7])

I fully understand what the code does, with h[4]=4^3-7=57 and h[6]=h[7]=big but I have the following issues:

  1. h[x_] does not function if I remove the brackets () ie h[x_]If[x > 5, Return[big]]; t = x^3; Return[t - 7] , what is the function of () in the code?
  2. Can someone also explain the significance of the semi-colons in this code, and what is it used instead of commas (which make the code not work). What are the benefits of using ; instead of , in code?
  • 4
    $\begingroup$ The code isn't that great; among other things, you have a global t in there which can be problematic if you're using t somewhere else. Try h[x_] := Block[{t}, If[x > 5, big, t = x^3; t - 7]] (but even that is not the best way to do it). Also, look up CompoundExpression[]. $\endgroup$ – J. M.'s technical difficulties Oct 14 '18 at 18:18
  • 4
    $\begingroup$ function definition has a high priority. Without the () the function definition would end at the first semicolon. With the () the function definition is the whole line. The If[] tests x and potentially bails out with the value big. If it doesn't bail out then the t=x^3;Return[t-7] is all done. Be cautious with Return because people have reported problems with that. $\endgroup$ – Bill Oct 14 '18 at 18:21

I might try to write the function a bit more simply as:

h[x_] := If[x > 5, big, x^3 - 7]

Then you can see it working by evaluating on the first 8 integers:

h /@ Range[8]
{-6, 1, 20, 57, 118, big, big, big}
| improve this answer | |
  • $\begingroup$ Nit-picky: To get exactly the same functionality, you'd want something like If[TrueQ[x > 5], big, x^3 - 7], so that h[z] would return z^3 - 7 instead of an If[] statement. But I expect the OP hasn't thought through that case yet and is assuming x is a real number. $\endgroup$ – Michael E2 Oct 14 '18 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.