8
$\begingroup$

I would like to create a function with several expressions in the code body.

For example, I would like to write something like this, but which will actually work.

myFunction[x]:=
  y=x
  y=y+3;
  (y+3)^3

I know that I can do this :

myFunction[x]:=(y=x;y=y+3;(y+3)^3)

But it will be hardly writable if I have a lot of expression to evaluate.

How can I do it?

(I just installed Mathematica and read some tutorials on the internet so my knowledge is veeeeeery basic).

$\endgroup$
5
  • 1
    $\begingroup$ Use Module[{y},...] to make y a local variable. You can use newlines, they have no syntactical meaning. $\endgroup$
    – Felix
    Commented Feb 28, 2017 at 15:00
  • $\begingroup$ You mean I should write : myFunction[x]:=Module[{y},y=x;y=y+3;(y+3)^3] And I can do newline between my ";" ? $\endgroup$
    – StarBucK
    Commented Feb 28, 2017 at 15:04
  • $\begingroup$ Take a look reference.wolfram.com/language/howto/… and mathematica.stackexchange.com/a/39464/5478 for more basic tutorials. $\endgroup$
    – Kuba
    Commented Feb 28, 2017 at 15:04
  • $\begingroup$ @Felix in cells they have, unless they are inside expressions. $\endgroup$
    – Kuba
    Commented Feb 28, 2017 at 15:08
  • 3
    $\begingroup$ Yes, within Module (or simply parentheses for that matter) you can use a newline for spacing, but you still need ; (CompoundExpression) or you end up multiplying expressions unintentionally. Please see (41091) for more. $\endgroup$
    – Mr.Wizard
    Commented Feb 28, 2017 at 15:11

1 Answer 1

7
$\begingroup$

You should write your function like so:

myFunction[x_] :=
  Module[{y},
    y = x;
    y = y + 3;
    (y + 3)^3]

Note the underscore in x_. This makes x into a formal argument that will not be confused with any definition of x you might have made.

Then, even when x and y have global values they will not interfere with either the proper definition of myFunction nor with calls to it.

x = 42; y = 43;
myFunction[1]

343

You can read more about defining functions here

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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