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  
        ,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.


1 Answer 1


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."]];


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!"];
  • $\begingroup$ Yes! That's exactly what I was looking for. Thank you very much! $\endgroup$
    – aalajmi
    Apr 3, 2018 at 2:14
  • $\begingroup$ @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. $\endgroup$
    – eyorble
    Apr 3, 2018 at 2:30

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.