# Defining general type of functions

In Mathematica the term "function" refers to an expression that is evaluated given an input, and has a return value.

I was wondering if it's possible to define functions in the C++ sense, without using any external assistance.

Example of what I'm trying to do: Say I want to write a function EvenOdd[x] defined as below:

      {
If[ x \[Element] Integers,
If[GCD[x,2]==1, Print[x, " is an odd number"], Print[x , " is an even
number"]
,Print[x , " is not an integer"]
]
}


This function doesn't have a return value, rather it executes a code given an input (the functions I'm thinking about doesn't necessarily need an input) . While the example I gave can be easily worked around using normal functions, it wouldn't be good enough in general.

I feel like Mathematica should already have some kind of ability to do this, I'm just not sure what is the terminology used for this situation.

There is a significant semantic argument as to whether what you're asking for is appropriately termed a "function". What you're requesting is, in C++ terms, a function of type void. However, overlooking that, it is perfectly possible to implement imperative subroutines of that sort in Mathematica. In fact your suggested code is essentially just lacking a name to call it by:

evenodd[x_] := (
If[x \[Element] Integers,
If[GCD[x, 2] == 1, Print[ToString[x] <> " is an odd integer."],
Print[ToString[x] <> " is an even integer."]],
Print[ToString[x] <> " is not an integer."]];
);

evenodd[3]


3 is an odd integer.

Note the use of := (SetDelayed) in the definition: that means that the code on the right hand side is evaluated in full every time the evenodd[x_] pattern appears, using the given x.

Similarly, imperative subroutines which take no arguments can be defined directly:

helloworld := Print["Hello world!"];

• Yes! That's exactly what I was looking for. Thank you very much! – aalajmi Apr 3 '18 at 2:14
• @aalajmi You're welcome, though if you find yourself using that often in Mathematica, I would recommend considering whether Mathematica is the best language for your project. A lot of Mathematica's abilities come from its functions. It supports these paradigms, but it can't support them as intrinsically. – eyorble Apr 3 '18 at 2:30