2
$\begingroup$

I'd like to have something like:

Switch[x,
  10, a = 3; b = 7,
  >10, a = 5; c = 6,
  _, a = 7; d = 12, b = 1];

I can't seem to get this to work.

$\endgroup$

closed as off-topic by 2012rcampion, rcollyer, m_goldberg, bbgodfrey, Bob Hanlon Apr 28 '15 at 21:49

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – 2012rcampion, rcollyer, m_goldberg, bbgodfrey, Bob Hanlon
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    $\begingroup$ Switch takes patterns. You want a pattern like x_ /; x > 10. $\endgroup$ – 2012rcampion Apr 28 '15 at 18:15
  • 3
    $\begingroup$ The function you are looking for is Which $\endgroup$ – m_goldberg Apr 28 '15 at 18:58
  • $\begingroup$ @2012rcampion - I can't figure out how to use that pattern in Switch. Can you give me a short example? $\endgroup$ – Mitchell Kaplan Apr 28 '15 at 20:13
  • $\begingroup$ Switch[x, 10, a = 3; b = 7, x_ /; x > 10, a = 5; c = 6, _, a = 7; d = 12, b = 1]: Use it like any other pattern. $\endgroup$ – 2012rcampion Apr 28 '15 at 21:06
  • 1
    $\begingroup$ I appreciate the help - it gets me what I needed - thanks! Putting it on hold seems kind of harsh. I see that I have a typo in my example with ",b=1". Not really relevant to the problem. The ">10" in the example was to demonstrate what I was trying to accomplish - I knew that it was not correct. As far as being easy to find in the documentation, I looked for quite a while. It didn't seem easy to me. Clearly I didn't know how to use a pattern for this. I've used them for arguments, and rules. I now know how to use a pattern in this context. Thanks again for the help, but ouch! $\endgroup$ – Mitchell Kaplan Apr 29 '15 at 0:16
5
$\begingroup$

It can be done with Switch, but that would be an awkward application of Switch.

Clear[a, b, c, d];
With[{x = 42},
  Switch[x,
    _?(# == 10 &), a = 3; b = 7; "==10",
    _?(# > 10 &), a = 5; c = 6; ">10",
    _, a = 7; d = 12; b = 1; "Otherwise"]]
">10"
 {a, b, c, d}
{5, b, 6, d}

However, Which is a better choice

Clear[a, b, c, d];
With[{x = 42},
  Which[
    x == 10, a = 3; b = 7; "==10",
    x > 10, a = 5; c = 6; ">10",
    True, a = 7; d = 12; b = 1; "Otherwise"]]
">10"
 {a, b, c, d}
{5, b, 6, d}
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.