Re: If without else
- To: mathgroup at smc.vnet.net
- Subject: [mg113030] Re: If without else
- From: Hugo Touchette <hugo.touchette at googlemail.com>
- Date: Tue, 12 Oct 2010 04:22:08 -0400 (EDT)
- References: <i8ukmb$odm$1@smc.vnet.net>
On Oct 11, 10:16 am, Sebastian Schmitt <sschm... at physi.uni- heidelberg.de> wrote: > Dear all! > > (I recycle my disclaimer.) > > I'm new to Mathematica with a background mostly in C++. Many times I > have the impression that my style is not natural-Mathematica > (Mathematicaesque so to say). > > I have a question to the usage of the If condition. > > In[72] := x = 2; b = 3; > > In[73] := If[b > 2, x = 10,]; x > > Out[73] = 10 > > In[74] := If[b > 3, x = 20,]; x > > Out[74] = 10 > > Is it good-practice to leave the "else" empty? Is > > x := 10 /; b > 2 > > what I'm looking for? > > Thanks in advance, > > Sebastian Dear Sebastian, The /; notation is for patterns defined with a condition, not conditional execution (in the sense of programming). For example, with x:=10/;b>2 you define a delayed replacement (x to be 10) on the condition that b>2. Here x:=10 is the pattern. If you want to execute something upon some conditions, then you really need to use 'If'. For example, Test[x_] := Module[{}, Print["Positive"] /; x > 0; Print["Even"] /; EvenQ[x]; ] doesn't do probably what you expect. What you want is Test[x_] := Module[{}, If[x > 0, Print["Positive"]]; If[EvenQ[x], Print["Even"]]; ] I hope this helps. oguh