6
$\begingroup$

I'm having trouble with replacements involving Or. I think the trouble mainly comes from the fact that you can't simply replace Or[a_] -> a, since a is often an invalid expression (like b, c). I.e. List[Or[a, b]] /. Or[a,b] -> a, b gives an error.

I have expressions inside lists such as {a, Or[b, c], d} - but also expressions such as {a, Or[b, c]} etc. I want to find a good way to replace the Or[a, b] with a, b - this should be possible since everything is happening inside a list such that it is okay that a, b isn't a valid expression on its own. It will end up in something like {x,a,b,z}.

I have expressions like:

{{m[3]->0,mbar[3]->2},{m[3]->1,mbar[3]->1}||{m[3]->2,mbar[3]->0},id[1]}

Or in FullForm:

List[List[Rule[m[3],0],Rule[mbar[3],2]],Or[List[Rule[m[3],1],Rule[mbar[3],1]],List[Rule[m[3],2],Rule[mbar[3],0]]],id[1]]

What do you do with these annoying Or's (which I get from Solve/Reduce and are thus forced upon me)?

I can find solutions for specific cases (List[x_, Or[a_, b_], z_] -> List[x, a, b, z]), but I would prefer a solution that does not involve looking at the precise structure of every object that involves Or. The whole point is that I need the replacements to work on things that get spit out by reduce without doing it by hand.

Note: The structure should not vary very wildly however. I expect no Ors inside Ors and only a combination of Lists and Rules and numbers.

$\endgroup$
4
  • $\begingroup$ Is {{m[3] -> 0, mbar[3] -> 2}, {m[3] -> 1, mbar[3] -> 1} || {m[3] -> 2, mbar[3] -> 0}, id[1]} /. Or[a_, b_] :> Sequence @@ {a, b} what you want? $\endgroup$ – grbl Dec 2 '16 at 23:54
  • $\begingroup$ expression /. Or -> Sequence $\endgroup$ – corey979 Dec 3 '16 at 0:00
  • $\begingroup$ @corey979 yes, much more elegant :-) $\endgroup$ – grbl Dec 3 '16 at 0:07
  • $\begingroup$ @corey979 Yes great, thank you. I thought there had to be a simple way to do this. Thanks, I didn't know Sequence. What should I do now about the question? Is this question to pointless and should I delete it? Or do you want to post this as an answer so that I can accept it? $\endgroup$ – Kvothe Dec 3 '16 at 0:18
7
$\begingroup$

You can use ReplaceAll (/.) to replace any Head with another. In combination with Sequence:

{a, Or[b, c], d} /. Or -> Sequence

{a, b, c, d}

$\endgroup$
1
$\begingroup$

You can also use Block to temporarily set Or to Sequence:

exp = {{m[3] -> 0, mbar[3] -> 2}, 
       {m[3] -> 1, mbar[3] -> 1} || {m[3] -> 2, mbar[3] -> 0}, id[1]};

Block[{Or = Sequence}, exp]

{{m[3] -> 0, mbar[3] -> 2}, {m[3] -> 1, mbar[3] -> 1}, {m[3] -> 2, mbar[3] -> 0}, id[1]}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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