# Use conditional expression inside With

I want to assign a number to an internal variable, depending if a specific option has been given, but it seems to fail. Something like:

paropts={a->1, b->2, c->3}

myFunction[t,  opts:OptionsPattern[paropts]]:=
With[{If[OptionValue[a],x=a/t,x=1/t]},y=x+OptionValue[c]]


I know the syntax is quite wrong here, but I just want to show the concept. If the option "a" is given then use it to calculate x, otherwise use only 1/t.

That means the function should able to work also if at the beginning my opts are:

paropts={b->2, c->3}


I want to do it as easy as possible and other forms I have tried do not work. I also need to keep the structure of the paropts rules as I have them now, because I use them in many other functions.

It would also be helpful to do it with Block or something else.

Thanks,

S

I am not sure if I completely understood your problem, but maybe the following is what you are looking for:

myFunction[t_, opts : OptionsPattern[paropts]] :=
Quiet[With[{x = If[OptionValue[a] =!= a, OptionValue[a]/t, 1/t]}, x + OptionValue[c]]]


It works both when the option a is set, either in paropts or in the function call, or not. I also added an underscore to t.

• Thanks! I think that's the solution, checking if OptionValue does not return the name of the option itself. I think I am safe here, since I use strictly numbers for the options. Oct 15, 2014 at 11:58

Unfortunately your code is too incomplete to test, but the following should do what you want:

myFunction[t, opts:OptionsPattern[paropts]]:=
With[{x = If[OptionValue[a], a/Optionvalue[b], 1/OptionValue[b]]},
y=x+OptionValue[c]]

• Hi, thanks for your comment. Yes, I will edit and simplify the function so that it works. But I think your solution is still not working for me. Oct 15, 2014 at 10:41
• I edited my question so that it is a bit more clear! Thanks! Oct 15, 2014 at 10:44