7
$\begingroup$

I have a list with this format {integer, sign, integer, sign, integer}, sign being one of these: Plus, Subtract, Times, Divide. For example, let's say:

list = {1, Plus, 2, Times, 3};

I'm searching for something that would return the value of that expression, taking into account the precedence of each.

At first I tried to do something like:

list[[1]]~list[[2]]~list[[3]]~list[[4]]~list[[5]]

But the answer to this list using this method would be $(1 + 2) \times 3 = 3 \times 3 = 9$, where it should have been $1 + 2 \times 3 = 1 + 6 = 7$

$\endgroup$
  • 3
    $\begingroup$ ToExpression[StringTake[StringReplace[ToString[{1, Plus, 2, Times, 3}/. {Plus -> "+", Times -> "*", Divide -> "/", Minus -> "-"}], "," -> ""], {2, -2}]] $\endgroup$ – Coolwater Jun 18 '15 at 19:01
  • $\begingroup$ @Coolwater that's quite nice. Why don't you write it up as an answer instead? $\endgroup$ – MarcoB Jun 18 '15 at 19:09
  • $\begingroup$ Pretty sure this is a dupe… I just can't find it. $\endgroup$ – J. M. will be back soon Jun 18 '15 at 21:16
4
$\begingroup$

This solution may be simple and rather "robust":

ToExpression[
  StringJoin[ToString /@ list /. {"Plus" -> "+", "Times" -> "*"}]
]

You may try it on:

list = {1, Plus, 2, Times, 3, Plus, "PlusPlus"}

where it correctly returns:

PlusPlus+7
$\endgroup$
6
$\begingroup$

I'm totally cheating here, but you can use SemanticInterpretation in v10 to get you there.

SemanticInterpretation[StringRiffle[{1, Plus, 2, Times, 3}, " "]]

7

:)

$\endgroup$
  • $\begingroup$ This deserves sooo many upvotes... $\endgroup$ – kale Jun 18 '15 at 20:24
  • $\begingroup$ I have v10 but i didn't know this cool $\endgroup$ – Coolwater Jun 18 '15 at 20:30
  • $\begingroup$ For some reason, in my v10 I don't have StringRiffle. Someone knows why? $\endgroup$ – Garmekain Jun 18 '15 at 21:24
  • 1
    $\begingroup$ @Garmekain StringRiffle was a 10.1 introduction. Try StringJoin@Riffle instead. $\endgroup$ – kale Jun 18 '15 at 23:35
5
$\begingroup$
list //. ({x___, PatternSequence[a_, u : #, b_], y___} :> 
         {x, u[a, b], y} & /@ {(Times | Divide), (Plus | Subtract)})

(*  {7} *)

f[list_] := list //. ({x___, PatternSequence[a_, u : #, b_], y___} :> 
                      {x, u[a, b], y} & /@ {(Times | Divide), (Plus | Subtract)})

{#, f@#} & /@ (Riffle[{a, b, c}, #] & /@ Tuples[{Times, Divide, Plus, Subtract}, 2]) // 
                                                                                  Grid

Mathematica graphics

$\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.