# Evaluate a expression split in a list

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[]~list[]~list[]~list[]~list[]


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$

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

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


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

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


7

:)

• This deserves sooo many upvotes... – kale Jun 18 '15 at 20:24
• I have v10 but i didn't know this cool – Coolwater Jun 18 '15 at 20:30
• For some reason, in my v10 I don't have StringRiffle. Someone knows why? – Garmekain Jun 18 '15 at 21:24
• @Garmekain StringRiffle was a 10.1 introduction. Try StringJoin@Riffle instead. – kale Jun 18 '15 at 23:35
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 