#!/usr/bin/env tclsh proc calculate {s} { # puts "calculate: $s" while {[string match *(* $s]} { # Find the first ) and the ( which matches it. set i 0 foreach c [split $s {}] { switch -- $c { ( {set left $i} ) {set right $i; break} } incr i } set n [calculate [string range $s $left+1 $right-1]] set s "[string range $s 0 $left-1]$n[string range $s $right+1 end]" # puts " reduce to: $s" } # Split expression into tokens. set tokens {} set tmp "" foreach c [split $s {}] { switch -glob -- $c { [0-9] {append tmp $c} default {lappend tokens $tmp $c; set tmp ""} } } lappend tokens $tmp # puts " tokens: $tokens" # Crunch. set n [lindex $tokens 0] # puts " n=$n" foreach t [lrange $tokens 1 end] { switch -- $t { + - * {set op $t} default { if {$op eq "+"} {incr n $t} else {set n [expr {$n * $t}]} } } # puts " t=$t n=$n" } return $n } set sum 0 while {[gets stdin line] >= 0} { if {$line eq ""} continue set line [string map {{ } {}} $line] incr sum [calculate $line] } puts $sum