Version 2 of Chemical arithmetics

Updated 2005-01-18 16:28:25 by dkf

if 0 {Richard Suchenwirth 2005-01-18 - Here's a little fun project that does "arithmetics" on chemical formulae (see example at bottom).}

 proc chem args {
   set mode   +
   set factor 1
   foreach arg $args {
      switch -regexp -- $arg {
         [+] - [-] {set mode $arg; set factor 1}
         ^[0-9]+$ {set factor $arg}
         default {
            foreach e [chem'split $arg] {
               inc a($e) [expr {$mode eq "-"?"-":""}]$factor
            }
         }
      }
   }
   set res ""
   foreach e [array names a] {
      if {$a($e)>0} {append res $e}
      if {$a($e)>1} {append res $a($e)}
   }
   set res
 }

if 0 {This splits a compound into its atoms, e.g.

 % chem'split H2SO4
 H H S O O O O

}

 proc chem'split compound {
   set res {}
   foreach {- el n} [regexp -all -inline {([A-Z][a-z]?)([0-9]*)} $compound] {
       if {$n eq ""} {set n 1}
       for {set i 0} {$i<$n} {incr i} {lappend res $el}
   }
   set res
 }

#-- A generic incrementor that creates a variable if it doesn't exist:

 proc inc {varName {amount 1}} {
    upvar 1 $varName var
    if ![info exists var] {set var 0}
    incr var $amount
 }

if 0 {Testing - still wrong (what are the rules of ordering elements in compounds?), but the element sum is right at least:

 % chem NaOH + HCl - H2O
 ClNa

Tcling chemists, take it with a grain of salt - and please contribute to this page ! :^)

DKF: Rules for ionic substances are that you start from most electropositive ion and go to most electronegative ion. I think. ;^)


Arts and crafts of Tcl-Tk programming }