Mathematica - can I define a block of code using a single variable?

It has been a while since I've used Mathematica, and I looked all throughout the help menu. I think one problem I'm having is that I do not know what exactly to look up. I have a block of code, with things like appending lists and doing basic math, that I want to define as a single variable.

My goal is to loop through a sequence and when needed I wanted to call a block of code that I will be using several times throughout the loop. I am guessing I should just put it all in a loop anyway, but I would like to be able to define it all as one function.

It seems like this should be an easy and straightforward procedure. Am I missing something simple?

Answers


This is the basic format for a function definition in Mathematica.

    myFunc[par1_,par2_]:=Module[{localVar1,localVar2}, 
statement1; statement2; returnStatement ]

Your question is not entirely clear, but I interpret that you want something like this:

facRand[] :=
 ({b, x} = Last@FactorInteger[RandomInteger[1*^12]]; Print[b])

Now every time facRand[] is called a new random integer is factored, global variables b and x are assigned, and the value of b is printed. This could also be done with Function:

Clear[facRand]

facRand =
 ({b, x} = Last@FactorInteger[RandomInteger[1*^12]]; Print[b]) &

This is also called with facRand[]. This form is standard, and allows addressing or passing the symbol facRand without triggering evaluation.


Need Your Help