Chemical calculator: Difference between revisions

m
m (Automated syntax highlighting fixup (second round - minor fixes))
m (→‎{{header|Wren}}: Minor tidy)
 
(19 intermediate revisions by 7 users not shown)
Line 152:
:*   Wikipedia article:   [https://en.wikipedia.org/wiki/Molecular_mass Molecular mass]
<br><br>
=={{header|ALGOL 68}}==
{{Trans|ALGOL W}}
<syntaxhighlight lang="algol68">
BEGIN # chemical calculator - calculate the molar mass of compounds #
# MODE to hold element symbols and masses #
MODE ATOM = STRUCT( STRING symbol, REAL mass, REF ATOM next );
 
# returns the molar mass of the specified molecule #
PROC molarmass = ( STRING molecule )REAL:
BEGIN
CHAR c;
BOOL had error := FALSE;
INT ch max = UPB molecule;
INT ch pos := LWB molecule - 1;
 
# reports a syntax error in the molecule starting at position ch pos #
PROC error = ( STRING message )VOID:
BEGIN
print( ( "Syntax error in molecule: ", molecule, message, newline ) );
print( ( " " ) );
FOR i TO ch pos - 1 DO print( ( " " ) ) OD;
print( ( "^", newline ) );
# ensure parsing stops #
had error := TRUE;
ch pos := ch max * 2
END # error # ;
# gets the next character from the molecule #
PROC next char = VOID:
c := IF ch pos +:= 1; ch pos > ch max THEN " " ELSE molecule[ ch pos ] FI;
# parses a compound: a sequence of element names and bracketed compounds, each with #
# an optional trailing repeat count #
PROC parse compound = REAL:
BEGIN
# parses an element symbol feom the molecule and returns its mass #
PROC parse atom = REAL:
BEGIN
STRING symbol := c;
next char;
FOR i TO 2 WHILE c >= "a" AND c <= "z" DO
symbol +:= c;
next char
OD;
# find the element in the table #
ATOM element := atoms[ ABS symbol[ LWB symbol ] - ABS "A" ];
WHILE IF element IS REF ATOM(NIL) THEN FALSE ELSE symbol OF element /= symbol FI DO
element := next OF element
OD;
IF element ISNT REF ATOM(NIL)
THEN # found the element # mass OF element
ELSE # unknown element #
ch pos -:= 1;
error( "Unrecognised element." );
0
FI
END # parse atom # ;
REAL mass := 0;
WHILE NOT had error AND ( ( c >= "A" AND c <= "Z" ) OR c = "(" ) DO
REAL item mass := 0;
IF c >= "A" AND c <= "Z" THEN item mass := parse atom
ELIF c = "(" THEN
# bracketed group #
next char;
item mass := parse compound;
IF IF ch pos > ch max THEN " " ELSE molecule[ ch pos ] FI /= ")" THEN
error( "Expected "")""." )
FI;
next char
FI;
IF c >= "0" AND c <= "9" THEN
# have a repeat count #
INT count := 0;
WHILE NOT had error AND c >= "0" AND c <= "9" DO
count *:= 10 +:= ABS c - ABS "0";
next char
OD;
item mass *:= count
FI;
mass +:= item mass
OD;
mass
END # parse compound # ;
next char;
REAL mass = parse compound;
IF ch pos <= ch max THEN error( "Unexpected text after the molecule." ) FI;
mass
END # molar mass # ;
# hash table of atome, hash is the first character of the symbol - "A" #
[ 0 : 25 ]REF ATOM atoms; FOR i FROM LWB atoms TO UPB atoms DO atoms( i ) := NIL OD;
BEGIN # setup element symbols and masses as specified in the task #
# adds an element and its mass to the atoms table #
OP / = ( STRING symbol, REAL mass )VOID:
BEGIN
INT index = ABS symbol[ LWB symbol ] - ABS "A";
atoms[ index ] := HEAP ATOM := ATOM( symbol, mass, atoms[ index ] )
END # / # ;
OP / = ( STRING symbol, INT mass )VOID: symbol / REAL(mass);
OP / = ( CHAR symbol, REAL mass )VOID: STRING(symbol) / mass;
PROC lanthanides = VOID:
BEGIN
"La"/138.90547;"Ce"/140.116 ;"Pr"/140.90766;"Nd"/144.242 ;"Pm"/145 ;
"Sm"/150.36 ;"Eu"/151.964 ;"Gd"/157.25 ;"Tb"/158.92535;"Dy"/162.5 ;
"Ho"/164.93033;"Er"/167.259 ;"Tm"/168.93422;"Yb"/173.054 ;"Lu"/174.9668;
SKIP
END # lanthanides # ;
PROC actinides = VOID:
BEGIN
"Ac"/227 ;"Th"/232.0377;"Pa"/231.03588;"U" /238.02891;"Np"/237 ;
"Pu"/244 ;"Am"/243 ;"Cm"/247; "Bk"/247; "Cf"/251 ;
"Es"/252 ;"Fm"/257 ;#Md ; No ; Lr ;#
SKIP
END # actinides # ;
"H" /1.008 ;"Li"/ 6.94 ;"Na"/22.98976928 ;"K" /39.0983 ;"Rb"/85.4678 ;"Cs"/132.90545196;"Fr"/223 ;
"Be"/ 9.0121831 ;"Mg"/24.305 ;"Ca"/40.078 ;"Sr"/87.62 ;"Ba"/137.327 ;"Ra"/226 ;
"Sc"/44.955908;"Y" /88.90584 ;lanthanides ;actinides;
"Ti"/47.867 ;"Zr"/91.224 ;"Hf"/178.49 ;# Rf #
"V" /50.9415 ;"Nb"/92.90637 ;"Ta"/180.94788 ;# Db #
"Cr"/51.9961 ;"Mo"/95.95 ;"W" /183.84 ;# Sg #
"Mn"/54.938044;#Tc #"Re"/186.207 ;# Bh #
"Fe"/55.845 ;"Ru"/101.07 ;"Os"/190.23 ;# Hs #
"Co"/58.933194;"Rh"/102.9055 ;"Ir"/192.217 ;# Mt #
"Ni"/58.6934 ;"Pd"/106.42 ;"Pt"/195.084 ;# Ds #
"Cu"/63.546 ;"Ag"/107.8682 ;"Au"/196.966569 ;# Rg #
"Zn"/65.38 ;"Cd"/112.414 ;"Hg"/200.592 ;# Cn #
"B" /10.81 ;"Al"/26.9815385 ;"Ga"/69.723 ;"In"/114.818 ;"Tl"/204.38 ;# Nh #
"C" /12.011 ;"Si"/28.085 ;"Ge"/72.63 ;"Sn"/118.71 ;"Pb"/207.2 ;# Fl #
"N" /14.007 ;"P" /30.973761998;"As"/74.921595;"Sb"/121.76 ;"Bi"/208.9804 ;# Ms #
"O" /15.999 ;"S" / 32.06 ;"Se"/78.971 ;"Te"/127.6 ;"Po"/209 ;# Lv #
"F" /18.998403163;"Cl"/35.45 ;"Br"/79.904 ;"I" /126.90447;"At"/210 ;# Ts #
"He"/4.002602;"Ne"/20.1797 ;"Ar"/39.948 ;"Kr"/83.798 ;"Xe"/131.293 ;"Rn"/222 ;# Og #
# --- hypothetical eigth period elements --/ # "Uue"/315;"Ubn"/299;
SKIP
END;
BEGIN # test cases #
PROC test = ( REAL expected mass, STRING molecule )VOID:
BEGIN
REAL mass = molar mass( molecule );
STRING pad = IF INT length = ( UPB molecule - LWB molecule ) + 1;
length > 20
THEN ""
ELSE ( 20 - length ) * " "
FI;
print( ( newline, pad, molecule, ":", fixed( mass, -9, 3 ) ) );
REAL diff = expected mass - mass;
IF diff > 1e-12 OR diff < -1e-12 THEN
print( ( " expected:", fixed( expected mass, -9, 3 ) ) )
FI
END # test # ;
test( 1.008, "H" ); test( 2.016, "H2" ); test( 18.015, "H2O" );
test( 142.03553856000002, "Na2SO4" ); test( 84.162, "C6H12" );
test( 186.29499999999996, "COOH(C(CH3)2)3CH3" ); test( 350.45, "UueCl" )
END
END
</syntaxhighlight>
{{out}}
<pre>
H: 1.008
H2: 2.016
H2O: 18.015
Na2SO4: 142.036
C6H12: 84.162
COOH(C(CH3)2)3CH3: 186.295
UueCl: 350.450
</pre>
 
=={{header|ALGOL W}}==
Algol W has fixed length strings and no regular expressions, this parses the molecule with a simple recursive descent parser.<br>
Line 187 ⟶ 351:
real procedure parseCompound ; begin
real mass, itemMass;
% parses an element symbol fromfeom the molecule and returnsretutns its mass %
real procedure parseAtom ; begin
string(3) symbol;
Line 265 ⟶ 429:
A("Es",252 );A("Fm",257 ); % Md % %, No % % Lr %
end Actinides ;
A("Li",real 6.94 )CsMass;A("Na",22.98976928 );A("K",CsMass 39.0983:= );A("Rb", 85.4678 );A("Cs",132.90545196);A("Fr", 223 );
A("BeLi", 96.012183194 );A("MgNa",2422.305 98976928 );A("CaK",40.078 39.0983 );A("SrRb", 8785.62 4678 );A("BaCs",137.327 CsMass );A("RaFr", 226 223);
A("Be", 9.0121831 );A("Mg",24.305 );A("ScCa",4440.955908078 );A("YSr", 8887.90584);62 Lanthanides);A("Ba",137.327 Actinides);A("Ra",226);
A("TiSc",4744.867 955908);A("ZrY", 91.224 );A("Hf",17888.49 90584);Lanthanides; % Rf %Actinides;
A("VTi", 5047.9415867 );A("NbZr", 9291.90637224 );A("TaHf",180178.9478849 ); % Db Rf %
A("CrV",51 50.99619415 );A("MoNb", 9592.95 90637);A("WTa", 183180.84 94788 ); % Sg Db %
A("MnCr",5451.9380449961 );A("Mo", %95.95 Tc % );A("ReW",186 183.207 84 ); % Bh Sg %
A("FeMn",5554.845938044); % Tc );A("Ru",101.07 ); % A("OsRe",190186.23 207 ); % Hs Bh %
A("CoFe",5855.933194845 );A("RhRu",102101.905507 );A("IrOs",192190.217 23 ); % Mt Hs %
A("NiCo",58.6934 933194);A("PdRh",106102.42 9055 );A("PtIr",195192.084 217 ); % Ds Mt %
A("CuNi",6358.546 6934 );A("AgPd",107106.868242 );A("AuPt",196195.966569084 ); % Rg Ds %
A("ZnCu",6563.38 546 );A("CdAg",112107.414 8682 );A("HgAu",200196.592 966569); % Cn Rg %
A("B", 10.81 );A("Al",26.9815385 ); A("GaZn",6965.72338 );A("InCd",114112.818414 );A("TlHg",204200.38 592 ); % Nh Cn %
A("CB", 1210.01181 );A("SiAl",2826.085 9815385 );A("GeGa",7269.63 723 );A("SnIn",118114.71 818 );A("PbTl",207204.2 38 ); % Fl Nh %
A("NC", 1412.007011 );A("PSi", 3028.973761998085 );A("AsGe",7472.92159563 );A("SbSn",121118.7671 );A("BiPb",208207.98042 ); % Ms Fl %
A("ON", 1514.999007 );A("SP", 3230.06 973761998);A("SeAs",7874.971 921595);A("TeSb",127121.6 76 );A("PoBi",209 208.9804 ); % Lv Ms %
A("FO", 1815.998403163999 );A("ClS",35 32.4506 );A("BrSe",7978.904971 );A("ITe", 126127.904476 );A("AtPo",210 209 ); % Ts Lv %
A("NeF",20 18.1797 998403163);A("ArCl",3935.94845 );A("KrBr",8379.798904 );A("XeI",131 126.293 90447);A("RnAt",222 210 ); % Og Ts %
A("Ne",20.1797 );A("Ar",39.948 );A("Kr",83.798 );A("Xe",131.293 );A("Rn",222 ); % Og %
% ---------------- first period elements ---> % A("H", 1.008);A("He", 4.002602);
% --- hypothetical eigth period elements ---> % A("Uue",315 );A("Ubn",299 );
Line 313 ⟶ 478:
UueCl : 350.450
</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">test := ["H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O"
Line 1,318 ⟶ 1,484:
C27H46O -> 386.664
Uue -> 315.000</pre>
 
=={{header|Delphi}}==
{{trans|Go}}
Line 1,589 ⟶ 1,756:
No assertion errors.
 
<!--
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Chemical_calculator}}
In [http://wiki.formulae.org/Chemical_Calculator this] page you can see the solution of this task.
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
Fōrmulæ has a module for chemistry. Notice that it is not a library, it effectively adds chemical elements as first class citizens to the language, and useful functions that operate with them, for example, to get their atomic masses.
 
There is an expression for a '''homonuclear compound''', a compound made from the union of several atoms of the same element, such as O<sub>2</sub>
 
There is also an expression for a '''heteronuclear compound''', a compound made from the union of several atoms of different elements, such as NaCl
 
[[File: Fōrmulæ - Chemical calculator 01.png]]
 
'''Notes'''
 
* The Tag(Expression) expression retrieves the tag of an expression. For example, when it is called on an homonuclear compound expression, it retrieves the string expression representing the string "Chemistry.HomonuclearCompound"
 
* The |Expression| retrieves the cardinality of the expression, this is, the number of subexpressions it has. If the expression is a heteronuclear compound it gives the number of elements being composed.
 
* If the expression given as parameter is a heteronuclear compound expression, the molar mass is the sum of the molar masses of each component. Note that this function is recursively called.
 
* If the expression given as parameter is a homonuclear compound expression, the molar mass is the product of the number of the group (the second component) and the molar mass of the expression (the first component). Note that this function is recursively called.
 
* Elsewhere, the result is the call of the GetAtomicMass(Expression) with the expression given as parameter.
 
'''Test cases'''
 
[[File: Fōrmulæ - Chemical calculator 02.png]]
 
[[File: Fōrmulæ - Chemical calculator 03.png]]
 
'''Using it symbolically'''
 
Fōrmulæ is a symbolic language. Although chemical elements expressions are intended to be used to create chemical formulae, other expressions can be used, specially symbols, as in the following examples:
 
Example 1. Using a symbol to denote and unspecified number of repetitions in a homonuclear compound expression. For this exercise, n is a free symbol (a symbol with no associated value).
 
[[File: Fōrmulæ - Chemical calculator 04.png]]
 
[[File: Fōrmulæ - Chemical calculator 05.png]]
 
Example 2. Using a symbol to denote an unspecified chemical element. For this exercise, X is a free symbol (a symbol with no associated value).
 
[[File: Fōrmulæ - Chemical calculator 06.png]]
 
[[File: Fōrmulæ - Chemical calculator 07.png]]
 
Example 3. Using symbols to denote an unspecified chemical element and an unspecified number of repetitions. For this exercise, X and n are free symbols (symbols with no associated values).
 
[[File: Fōrmulæ - Chemical calculator 08.png]]
 
[[File: Fōrmulæ - Chemical calculator 09.png]]
 
Example 4. Using symbols to denote different unspecified chemical elements. For this exercise, X, Y and Z are free symbols (symbols with no associated values).
 
[[File: Fōrmulæ - Chemical calculator 10.png]]
 
[[File: Fōrmulæ - Chemical calculator 11.png]]
 
Example 5. Other combinations. For this exercise, X, Y, Z, n and m are free symbols (symbols with no associated values).
 
[[File: Fōrmulæ - Chemical calculator 12.png]]
 
[[File: Fōrmulæ - Chemical calculator 13.png]]
 
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
-->
=={{header|Go}}==
This doesn't use regular expressions, RPN or eval (which Go doesn't have). It's just a simple molar mass evaluator written from scratch.
Line 2,073 ⟶ 2,297:
invalid atom name starting here
</pre>
=={{header|J}}==
 
This could be done a bit more concisely, but it's not clear that that would be an advantage here.
 
<syntaxhighlight lang=J>do{{)n
H: 1.008, He: 4.002602, Li: 6.94, Be: 9.0121831,
B: 10.81, C: 12.011, N: 14.007, O: 15.999,
F: 18.998403163, Ne: 20.1797, Na: 22.98976928, Mg: 24.305,
Al: 26.9815385, Si: 28.085, P: 30.973761998, S: 32.06,
Cl: 35.45, K: 39.0983, Ar: 39.948, Ca: 40.078,
Sc: 44.955908, Ti: 47.867, V: 50.9415, Cr: 51.9961,
Mn: 54.938044, Fe: 55.845, Ni: 58.6934, Co: 58.933194,
Cu: 63.546, Zn: 65.38, Ga: 69.723, Ge: 72.63,
As: 74.921595, Se: 78.971, Br: 79.904, Kr: 83.798,
Rb: 85.4678, Sr: 87.62, Y: 88.90584, Zr: 91.224,
Nb: 92.90637, Mo: 95.95, Ru: 101.07, Rh: 102.9055,
Pd: 106.42, Ag: 107.8682, Cd: 112.414, In: 114.818,
Sn: 118.71, Sb: 121.76, I: 126.90447, Te: 127.6,
Xe: 131.293, Cs: 132.90545196, Ba: 137.327, La: 138.90547,
Ce: 140.116, Pr: 140.90766, Nd: 144.242, Pm: 145,
Sm: 150.36, Eu: 151.964, Gd: 157.25, Tb: 158.92535,
Dy: 162.5, Ho: 164.93033, Er: 167.259, Tm: 168.93422,
Yb: 173.054, Lu: 174.9668, Hf: 178.49, Ta: 180.94788,
W: 183.84, Re: 186.207, Os: 190.23, Ir: 192.217,
Pt: 195.084, Au: 196.966569, Hg: 200.592, Tl: 204.38,
Pb: 207.2, Bi: 208.9804, Po: 209, At: 210,
Rn: 222, Fr: 223, Ra: 226, Ac: 227,
Pa: 231.03588, Th: 232.0377, Np: 237, U: 238.02891,
Am: 243, Pu: 244, Cm: 247, Bk: 247,
Cf: 251, Es: 252, Fm: 257, Ubn: 299,
Uue: 315
}} rplc ':';'=:'; ',';'['; LF;''
 
NB. 0: punctuation, 1: numeric, 2: upper case, 3: lower case
ctyp=: e.&'0123456789' + (2*]~:tolower) + 3*]~:toupper
tokenize=: (0;(0 10#:10*do;._2{{)n
1.1 2.1 3.1 4.1 NB. start here
1.2 2.2 3.2 4.2 NB. punctuation is 1 character per word
1.2 2 3.2 4.2 NB. numeric characters are word forming
1.2 2.2 3.2 4 NB. upper case always begins a word
1.2 2.2 3.2 4 NB. lower case always continues a word
}});ctyp a.)&;:
 
molar_mass=: {{
W=.,0 NB. weight stack
M=.,1 NB. multiplier stack
digit=. (1=ctyp a.)#<"0 a.
alpha=. (2=ctyp a.)#<"0 a.
for_t.|.tokenize y do. select. {.;t
case. '(' do. W=. (M #.&(2&{.) W), 2}.W
M=. 1,2}.M
case. ')' do. W=. 0,W
M=. 1,M
case. digit do.
M=. (do;t),}.M
case. alpha do. W=. (({.W)+({.M)*do;t),}.W
M=. 1,}.M
case. do. NB. ignore irrelevant whitespace
end. end. assert. 1=#W
<.@+&0.5&.(*&1000){.W
}}
 
assert 1.008 = molar_mass('H') NB. hydrogen
assert 2.016 = molar_mass('H2') NB. hydrogen gas
assert 18.015 = molar_mass('H2O') NB. water
assert 34.014 = molar_mass('H2O2') NB. hydrogen peroxide
assert 34.014 = molar_mass('(HO)2') NB. hydrogen peroxide
assert 142.036 = molar_mass('Na2SO4') NB. sodium sulfate
assert 84.162 = molar_mass('C6H12') NB. cyclohexane
assert 186.295 = molar_mass('COOH(C(CH3)2)3CH3') NB. butyric or butanoic acid
assert 176.124 = molar_mass('C6H4O2(OH)4') NB. vitamin C
assert 386.664 = molar_mass('C27H46O') NB. cholesterol
assert 315 = molar_mass('Uue') NB. ununennium
</syntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
Line 2,269 ⟶ 2,568:
C27H46O -> 386.664
Uue -> 315.000</pre>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
Line 2,319 ⟶ 2,619:
</pre>
=={{header|jq}}==
[[Category:PEG]]
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
jq is well-suited to [[:Category:PEG|"Parsing Expression Grammars"]] (PEGs) so
this entry illustrates how to implement the chemical calculator using a PEG approach.
 
Line 2,402 ⟶ 2,703:
["DEBUG:",["Uue"]]
</pre>
 
=={{header|Julia}}==
Note that Julia's 64-bit floating point gets a slightly different result for one of the assertions, hence a small change in the last example. The function uses Julia's own language parser to evaluate the compound as an arithmetic expression.
Line 3,639 ⟶ 3,941:
C27H46O -> 386.664
Uue -> 315.000</pre>
 
=={{header|Rust}}==
Rust is precompiled for execution, so there is no runtime eval for arbitrary Rust code. The `eval` crate allows Rust to process syntax similar to JSON while executing.
This allows the example to run an `eval` on strings which have been first translated into numeric arithmetic.
<syntaxhighlight lang="rust">use regex::Regex;
use eval::{eval, to_value};
use aho_corasick::AhoCorasick;
 
const ELEMENTS: &[&str; 5] = &["H", "C", "O", "Na", "S",];
const WEIGHTS: &[&str; 5] = &["1.008", "12.011", "15.999", "22.98976928", "32.06",];
 
fn main() {
let test_strings = ["H", "H2", "H2O", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3"];
let test_values = [1.008, 2.016, 18.015, 142.03553856000002, 84.162, 186.29500000000002];
let ac = AhoCorasick::new(ELEMENTS).unwrap();
let regex1 = Regex::new(r"(?<num>\d+)").unwrap();
let regex2 = Regex::new(r"(?<group>[A-Z][a-z]{0,2}|\()").unwrap();
 
for (i, s) in test_strings.iter().enumerate() {
let s1 = regex1.replace_all(*s, "*$num");
let s2 = regex2.replace_all(&s1, "+$group");
let s3 = ac.replace_all(&s2, WEIGHTS).trim_start_matches("+").replace("(+", "(");
let mass: Result<eval::Value, eval::Error> = eval(&s3);
assert_eq!(mass, Ok(to_value(test_values[i])));
println!("The molar mass of {} checks correctly as {}.", s, test_values[i]);
}
}
</syntaxhighlight>{{out}}
<pre>
The molar mass of H checks correctly as 1.008.
The molar mass of H2 checks correctly as 2.016.
The molar mass of H2O checks correctly as 18.015.
The molar mass of Na2SO4 checks correctly as 142.03553856000002.
The molar mass of C6H12 checks correctly as 84.162.
The molar mass of COOH(C(CH3)2)3CH3 checks correctly as 186.29500000000002.
</pre>
 
=={{header|Swift}}==
 
Line 4,316 ⟶ 4,655:
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
import "./str" for Char, Str
 
var atomicMass = {
Line 4,490 ⟶ 4,829:
for (molecule in molecules) {
var mass = evaluate.call(replaceParens.call(molecule))
SystemFmt.print("%(Fmt.s(17, molecule))$17s -> %(Fmt$7.f(73f", massmolecule, 3))"mass)
}</syntaxhighlight>
 
Line 4,507 ⟶ 4,846:
Uue -> 315.000
</pre>
 
=={{header|zkl}}==
Really bad error checking
Line 4,561 ⟶ 4,901:
{ println(cstr," --> ",molarMass(cstr)) }</syntaxhighlight>
{{out}}
Weight of H = 1.008.
Weight of H2 = 2.016.
Weight of H2O = 18.015.
Weight of H2O2 = 34.014.
Weight of (HO)2 = 34.014.
Weight of Na2SO4 = 142.036.
Weight of C6H12 = 84.162.
Weight of COOH(C(CH3)2)3CH3 = 186.295.
Weight of C6H4O2(OH)4 = 176.124.
Weight of C27H46O = 386.664.
Weight of Uue = 315.000.
<pre>
H --> 1.008
Line 4,569 ⟶ 4,920:
COOH(C(CH3)2)3CH3 --> 186.295
</pre>
=={{header|X-script}}==
<syntaxhighlight lang="zkl">
 
<var $weighttab[],
-H:1.008|He:4.002602|Li:6.94|Be:9.0121831|B:10.81|C:12.011|N:14.007|O:15.999|F:18.998403163|
-Ne:20.1797|Na:22.98976928|Mg:24.305|Al:26.9815385|Si:28.085|P:30.973761998|S:32.06|Cl:35.45|
-K:39.0983|Ar:39.948|Ca:40.078|Sc:44.955908|Ti:47.867|V:50.9415|Cr:51.9961|Mn:54.938044|
-Fe:55.845|Ni:58.6934|Co:58.933194|Cu:63.546|Zn:65.38|Ga:69.723|Ge:72.63|As:74.921595|Se:78.971|
-Br:79.904|Kr:83.798|Rb:85.4678|Sr:87.62|Y:88.90584|Zr:91.224|Nb:92.90637|Mo:95.95|Ru:101.07|
-Rh:102.9055|Pd:106.42|Ag:107.8682|Cd:112.414|In:114.818|Sn:118.71|Sb:121.76|I:126.90447|Te:127.6|
-Xe:131.293|Cs:132.90545196|Ba:137.327|La:138.90547|Ce:140.116|Pr:140.90766|Nd:144.242|Pm:145|
-Sm:150.36|Eu:151.964|Gd:157.25|Tb:158.92535|Dy:162.5|Ho:164.93033|Er:167.259|Tm:168.93422|
-Yb:173.054|Lu:174.9668|Hf:178.49|Ta:180.94788|W:183.84|Re:186.207|Os:190.23|Ir:192.217|Pt:195.084|
-Au:196.966569|Hg:200.592|Tl:204.38|Pb:207.2|Bi:208.9804|Po:209|At:210|Rn:222|Fr:223|Ra:226|Ac:227|
-Pa:231.03588|Th:232.0377|Np:237|U:238.02891|Am:243|Pu:244|Cm:247|Bk:247|Cf:251|Es:252|Fm:257|
-Ubn:299|Uue:315
->
<var $level>
<var $stackTab[]>
 
chemicalCalculator.x
--------------------
 
<def charcode,<htod <stoh $1>>>
<var $name>
<var $multiplier>
<var $unusedCharacters>
 
!"<in <sp 1>,string>
-<set $level,0>
-<set $stackTab[0],0>
-"!
 
(* 1-3 characters in a row plus optional multipier. Examples: "Uee", "NaO", "COO", "Na2" *)
?"<format l><opt <format l>><opt <format l>><opt <integer>>"?
!"
-<set $name,<p 1>>
-<set $multiplier,1>
-<set $unusedCharacters,>
-<ifis <p 2>,
--<if <charcode <p 2>>'>=96,
---(* Lower case char - add to name. *)
---<append $name,<p 2>>
---<ifis <p 3>,
----<if <charcode <p 3>>'>=96,
-----(* Lower case char again - add to name. *)
-----<append $name,<p 3>>
-----,{else}
-----(* Not for this name, put in unread buffer. *)
-----<append $unusedCharacters,<p 3>>
----->
---->
---,{else}
---(* Not for this name, put in unread buffer. *)
---<append $unusedCharacters,<p 2>>
---<append $unusedCharacters,<p 3>>
--->
-->
-(* Multiplier. *)
-<set $multiplier,1>
-<ifis <p 4>,
--<ifis $unusedCharacters,
---(* Multiplier is not for this name, put in unread buffer. *)
---<append $unusedCharacters,<p 4>>
---,{else}
---(* Use as multiplier. *)
---<set $multiplier,<p 4>>
--->
-->
-
-(* Unread unused characters. *)
-<unread $unusedCharacters>
-
-(* Update weight. *)
-<update $stackTab[$level],+$weightTab[$name]*$multiplier,3>
-"!
 
(* Beginning of group. *)
?"("?
!"
-<update $level,+1>
-<set $stackTab[$level],0>
-"!
 
(* End of group. *)
?")<opt <integer>>"?
!"
-<ifis <p 1>,
--<update $stackTab[$level],*<p 1>,3>
-->
-<update $stackTab[<calc $level-1>],+$stackTab[$level],3>
-<update $level,-1>
-"!
 
?"<eof>"?
!"
-<wcons Weight of <sp 1> = $stackTab[$level].>
-<r>
-"!
 
!"<r $stackTab[$level]>"!
--------------
 
<function assert,
-<unless $1=<c chemicalCalculator,$2>,<wcons <c chemicalCalculator,$2>!= $1.>>
->
 
<assert 1.008,H>
<assert 2.016,H2>
<assert 18.015,H2O>
<assert 34.014,H2O2>
<assert 34.014,(HO)2>
<assert 142.036,Na2SO4>
<assert 84.162,C6H12>
<assert 186.295,COOH(C(CH3)2)3CH3>
<assert 176.124,C6H4O2(OH)4>
<assert 386.664,C27H46O>
<assert 315 ,Uue>
</syntaxhighlight>
 
{{out}}
Weight of H = 1.008.<br>
Weight of H2 = 2.016.<br>
Weight of H2O = 18.015.<br>
Weight of H2O2 = 34.014.<br>
Weight of (HO)2 = 34.014.<br>
Weight of Na2SO4 = 142.036.<br>
Weight of C6H12 = 84.162.<br>
Weight of COOH(C(CH3)2)3CH3 = 186.295.<br>
Weight of C6H4O2(OH)4 = 176.124.<br>
Weight of C27H46O = 386.664.<br>
Weight of Uue = 315.000.
9,476

edits