Ruslan
Ruslan

Reputation: 19120

Mathematica: conditional "compilation"

I'm trying to make a conditinal expression which would initialize some functions, variables etc.. Something which would look like this in C:

#if option==1
  int foo(int x){/*some code here*/}
  int q=10;
#else
  char foo(int x){/*some other code*/}
  double q=3.141592;
#endif
use_q(q);
f(some_var);

In Mathematica I've tried using If, like this:

If[option==1,
foo[x_]=some_expression1;
q=10;
,
foo[x_]=some_expression2;
q=3.141592;
]
use_q[q];
f[some_var];

But the result is that functions' arguments are colored red, and nothing gets initialized or computed inside If. So, how should I do instead to get conditional "compilation"?

Upvotes: 0

Views: 403

Answers (2)

Verbeia
Verbeia

Reputation: 4420

This sounds like something that would be better done as a function with an option, for example

Options[myfunction,{Compiled->False}]

myfunction[x_,opts:OptionsPattern[]]:=
   With[{comp= TrueQ[OptionValue[Compiled]]},
    If[comp, compiledFunction[x], notcompiledFunction[x] ]]

(The local constant comp within the With statement is not strictly necessary for this example but would be useful if your code is at all complex and you use this conditional more than once.)

I do not recommend defining different cases of a function inside an If[] statement. You would be better off using the built-in pattern-matching abilities in Mathematica. (See documentation here and especially here.)

Some useful documentation on options within functions can be found here, here and here.

Upvotes: 3

Leonid Shifrin
Leonid Shifrin

Reputation: 22579

Several things:

  1. Do not use blanks (underscores) in variable names - in Mathematica these are reserved symbols, representing patterns.

  2. In case you condition does not evaluate to True or False, If does not evaluate either.

Thus:

In[12]:= If[option==1,Print["1"],Print["Not 1"]]
Out[12]= If[option==1,Print[1],Print[Not 1]]

thus your result. Red colred arguments are not the issue in this particular case. You should either use === in place of ==, or TrueQ[option==1], to get what you want. Have a look here, for more information.

Upvotes: 7

Related Questions