Chemical calculator: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(→{{header|jq}}: correction) |
m (→{{header|Wren}}: Minor tidy) |
||
(26 intermediate revisions by 11 users not shown) | |||
Line 136:
;Examples:
<
assert 2.016 == molar_mass('H2') # hydrogen gas
assert 18.015 == molar_mass('H2O') # water
Line 146:
assert 176.124 == molar_mass('C6H4O2(OH)4') # vitamin C
assert 386.664 == molar_mass('C27H46O') # cholesterol
assert 315 == molar_mass('Uue') # ununennium</
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>
Some error checking is included.
<
% calculates the molar mass of the specified molecule %
real procedure molar_mass ( string(256) value molecule ) ; begin
Line 188 ⟶ 351:
real procedure parseCompound ; begin
real mass, itemMass;
% parses an element symbol
real procedure parseAtom ; begin
string(3) symbol;
Line 266 ⟶ 429:
A("Es",252 );A("Fm",257 ); % Md % %, No % % Lr %
end Actinides ;
A("
A("Be", 9.0121831 );A("Mg",24.305
A("
A("
A("
A("
A("
A("
A("
A("
A("
A("
A("
A("
A("
A("
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 303 ⟶ 467:
test( 186.29499999999996, "COOH(C(CH3)2)3CH3" ); test( 350.45, "UueCl" );
end
end.</
{{out}}
<pre>
Line 315 ⟶ 479:
</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">test := ["H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O"
, "Uue", "C6H4O2(O)H)4", "X2O"]
for i, str in test
result .= str "`t`t`t> " Chemical_calculator(str) "`n"
MsgBox, 262144, , % result
return
Chemical_calculator(str){
if (RegExReplace(str, "\(([^()]|(?R))*\)")~="[()]")
return "Invalid Group"
oAtomM := {"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}
str := RegExReplace(str, "\d+", "*$0")
while InStr(str, "("){
pos := RegExMatch(str, "\(([^()]+)\)\*(\d+)", m)
m1 := RegExReplace(m1, "[A-Z]([a-z]*)", "$0*" m2)
str := RegExReplace( str, "\Q" m "\E", m1,, 1, pos)
}
str := Trim(RegExReplace(str, "[A-Z]", "+$0"), "+")
sum := 0
for i, atom in StrSplit(str, "+"){
prod := 1
for j, p in StrSplit(atom, "*")
prod *= (p~="\d+") ? p : 1
atom := RegExReplace(atom, "\*\d+")
if !oAtomM[atom]
return "Invalid atom name"
sum += oAtomM[atom] * prod
}
return str " > " sum
}</syntaxhighlight>
{{out}}
<pre>H > H > 1.008000
H2 > H*2 > 2.016000
H2O > H*2+O > 18.015000
H2O2 > H*2+O*2 > 34.014000
(HO)2 > H*2+O*2 > 34.014000
Na2SO4 > Na*2+S+O*4 > 142.035539
C6H12 > C*6+H*12 > 84.162000
COOH(C(CH3)2)3CH3 > C+O+O+H+C*3+C*3*2+H*3*2*3+C+H*3 > 186.295000
C6H4O2(OH)4 > C*6+H*4+O*2+O*4+H*4 > 176.124000
C27H46O > C*27+H*46+O > 386.664000
Uue > Uue > 315
C6H4O2(O)H)4 > Invalid Group
X2O > Invalid atom name</pre>
=={{header|C}}==
<
#include <stdlib.h>
#include <string.h>
Line 579 ⟶ 798:
dic = NULL;
return 0;
}</
{{out}}
<pre> H -> 1.008
Line 592 ⟶ 811:
C27H46O -> 386.664
Uue -> 315.000</pre>
=={{header|C sharp|C#}}==
{{trans|D}}
<
using System.Collections.Generic;
using System.Linq;
Line 785 ⟶ 1,003:
}
}
}</
{{out}}
<pre> H -> 1.008
Line 798 ⟶ 1,016:
C27H46O -> 386.664
Uue -> 315.000</pre>
=={{header|C++}}==
{{trans|C#}}
<
#include <iostream>
#include <map>
Line 998 ⟶ 1,215:
return 0;
}</
{{out}}
<pre> H -> 1.008
Line 1,011 ⟶ 1,228:
C27H46O -> 386.664
Uue -> 315.000</pre>
=={{header|CoffeeScript}}==
===No Regular Expression===
<
molar_mass = (s) ->
Line 1,045 ⟶ 1,261:
assert 176.124, molar_mass 'C6H4O2(OH)4' # Vitamin C
assert 386.664, molar_mass 'C27H46O' # Cholesterol
assert 315, molar_mass 'Uue'</
===Regular Expression===
{{trans|Julia}}
<
mul = (match, p1, offset, string) -> '*' + p1
Line 1,071 ⟶ 1,287:
assert 176.124, molar_mass('C6H4O2(OH)4') # Vitamin C
assert 386.664, molar_mass('C27H46O') # Cholesterol
assert 315, molar_mass('Uue')</
=={{header|D}}==
{{trans|Go}}
<
import std.conv;
import std.format;
Line 1,256 ⟶ 1,471:
}
writeln(atomicMass);
}</
{{out}}
<pre> H -> 1.008
Line 1,272 ⟶ 1,487:
=={{header|Delphi}}==
{{trans|Go}}
<syntaxhighlight lang="delphi">
program ChemicalCalculator;
Line 1,422 ⟶ 1,637:
readln;
end.
</syntaxhighlight>
Include file with Atomic Mass Constants ('''AtomicMass.inc''').
<syntaxhighlight lang="delphi">
const
ATOMIC_MASS_SIZE = 101;
Line 1,450 ⟶ 1,665:
226, 227, 232.0377, 231.03588, 238.02891, 237, 244, 243, 247, 247, 251, 252,
257, 315, 299);
</syntaxhighlight>
=={{header|Factor}}==
{{works with|Factor|0.98}}
<
infix.private kernel math.functions math.parser multiline
peg.ebnf qw sequences splitting strings words words.constant ;
Line 1,540 ⟶ 1,752:
} [ molar-mass 1e-5 approx-assert= ] assoc-each ;
MAIN: chemical-calculator-demo</
No assertion errors.
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Chemical_calculator}}
'''Solution'''
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]]
=={{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.
<
import (
Line 1,734 ⟶ 2,002:
fmt.Printf("%17s -> %7.3f\n", molecule, mass)
}
}</
{{out}}
Line 1,750 ⟶ 2,018:
Uue -> 315.000
</pre>
=={{header|Groovy}}==
{{trans|Java}}
<
class ChemicalCalculator {
Line 1,931 ⟶ 2,198:
}
}
}</
{{out}}
<pre> H -> 1.008
Line 1,944 ⟶ 2,211:
C27H46O -> 386.664
Uue -> 315.000</pre>
=={{header|Haskell}}==
Create a set of parsers for molecular formulae and their subparts. The parsers maintain a running total of the mass parsed so far. Use a '''Reader''' monad to store a map from atom names to their masses. The contents of the map are read from the file '''chemcalc_masses.in''', not shown here.
<syntaxhighlight lang="haskell">import Control.Monad (forM_)
import Control.Monad.Reader (Reader, ask, runReader)
import Data.Bifunctor (first)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Void (Void)
import System.Environment (getArgs)
import System.IO (IOMode(ReadMode), withFile)
import System.IO.Strict (hGetContents)
import Text.Megaparsec (ParsecT, (<|>), between, errorBundlePretty, getOffset,
many, option, runParserT, some, setOffset)
import Text.Megaparsec.Char (char, lowerChar, upperChar)
import Text.Megaparsec.Char.Lexer (decimal)
import Text.Printf (printf)
type Masses = Map String Double
type ChemParser = ParsecT Void String (Reader Masses) Double
-- Parse the formula of a molecule, returning the latter's total mass.
molecule :: ChemParser
molecule = sum <$> some (atomGroup <|> atom)
-- Parse an atom group, optionally followed by its count, returning its total
-- mass.
atomGroup :: ChemParser
atomGroup = mul <$> between (char '(') (char ')') molecule <*> option 1 decimal
-- Parse an atom name, optionally followed by a count, returning its total mass.
atom :: ChemParser
atom = mul <$> atomMass <*> option 1 decimal
-- Parse an atom name, returning its mass. Fail if the name is unknown.
atomMass :: ChemParser
atomMass = do
off <- getOffset
masses <- ask
atomName <- (:) <$> upperChar <*> many lowerChar
case M.lookup atomName masses of
Nothing -> setOffset off >> fail "invalid atom name starting here"
Just mass -> return mass
-- Given a molecular formula and a map from atom names to their masses, return
-- the the total molar mass, or an error message if the formula can't be parsed.
molarMass :: String -> String -> Masses -> Either String Double
molarMass file formula = first errorBundlePretty . runChemParser
where runChemParser = runReader (runParserT molecule file formula)
-- Read from a file the map from atom names to their masses.
getMasses :: FilePath -> IO Masses
getMasses path = withFile path ReadMode (fmap read . hGetContents)
mul :: Double -> Int -> Double
mul s n = s * fromIntegral n
main :: IO ()
main = do
masses <- getMasses "chemcalc_masses.in"
molecs <- getArgs
forM_ molecs $ \molec -> do
printf "%-20s" molec
case molarMass "<stdin>" molec masses of
Left err -> printf "\n%s" err
Right mass -> printf " %.4f\n" mass
</syntaxhighlight>
{{out}}
<pre>
H 1.0080
H2 2.0160
H2O 18.0150
H2O2 34.0140
(HO)2 34.0140
Na2SO4 142.0355
C6H12 84.1620
COOH(C(CH3)2)3CH3 186.2950
C6H4O2(OH)4 176.1240
C27H46O 386.6640
Uue 315.0000
(HOz)2
<stdin>:1:3:
|
1 | (HOz)2
| ^
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}}
<
import java.util.List;
import java.util.Map;
Line 2,128 ⟶ 2,555:
}
}
}</
{{out}}
<pre> H -> 1.008
Line 2,143 ⟶ 2,570:
=={{header|JavaScript}}==
<
const MASSES = {
C: 12.011,
Line 2,175 ⟶ 2,602:
for (let i = 0; i < formulae.length; i++)
console.log(`${getSubNums(formulae[i])}: ${getMolarMass(formulae[i]).toPrecision(3)}`);
</syntaxhighlight>
{{out}}
Line 2,191 ⟶ 2,618:
Uue: 315
</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,219 ⟶ 2,646:
'''The PEG grammar'''
<
parse("(?<e>^[A-Z][a-z]*)"); # greedy
Line 2,235 ⟶ 2,662:
(plus(EN) | Parenthesized | Formula)
// (plus(EN) | optional(Parenthesized))
// (Parenthesized | optional(Formula)) ;</
'''Evaluation of the parsed expression'''
Line 2,241 ⟶ 2,668:
'''The task expressed in terms of assertions'''
<syntaxhighlight lang="text"># A "debug" statement has been retained so that the parsed chemical formula can be seen.
def molar_mass(formula):
{remainder: formula} | Formula | .result | debug | eval;
def assert(a; b):
if (a - b)|length > 1e-3 then "\(a) != \(b)" else empty end;
def task:
Line 2,257 ⟶ 2,684:
assert( 84.162; molar_mass("C6H12")), # cyclohexane
assert( 186.295; molar_mass("COOH(C(CH3)2)3CH3")), # butyric or butanoic acid
assert( 176.124; molar_mass("C6H4O2(OH)4")), # vitamin C
assert( 386.664; molar_mass("C27H46O")), # cholesterol
assert( 315 ; molar_mass("Uue")) # ununennium
;</
{{out}}
As mentioned above, a "debug" statement has been retained so that the parsed chemical formula can be seen.
Line 2,279 ⟶ 2,706:
=={{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.
<
const He = 4.002602
const Li = 6.94
Line 2,392 ⟶ 2,819:
@assert 84.162 == molar_mass("C6H12")
@assert 186.29500000000002 == molar_mass("COOH(C(CH3)2)3CH3")
</syntaxhighlight>
No assertion errors.
=={{header|Kotlin}}==
{{trans|D}}
<
"H" to 1.008,
"He" to 4.002602,
Line 2,571 ⟶ 2,997:
println("$moleStr -> $massStr")
}
}</
{{out}}
<pre> H -> 1.008
Line 2,584 ⟶ 3,010:
C27H46O -> 386.664
Uue -> 315.000</pre>
=={{header|Lua}}==
{{trans|C#}}
<
["H"] = 1.008,
["He"] = 4.002602,
Line 2,764 ⟶ 3,189:
local mass = evaluate(replaceParens(molecule))
print(string.format("%17s -> %7.3f", molecule, mass))
end</
{{out}}
<pre> H -> 1.008
Line 2,777 ⟶ 3,202:
C27H46O -> 386.664
Uue -> 315.000</pre>
=={{header|Nim}}==
* Nim lacks runtime eval, that's the reason for so much code. (And me being a sloppy programmer)
* Also, seqs can't contain mixed types.
<
import tables, strutils, sequtils, math
Line 2,893 ⟶ 3,317:
assert 176.124 == molar_mass "C6H4O2(OH)4" # Vitamin C
assert 386.664 == molar_mass "C27H46O" # Cholesterol
assert 315 == molar_mass "Uue"</
=={{header|Perl}}==
===Grammar===
<
use warnings;
use List::Util;
Line 2,917 ⟶ 3,340:
for (<H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>) {
printf "%7.3f %s\n", $g->weight($_), $_
}</
===Regular Expression===
<
use warnings;
my %atomic_weight = < H 1.008 C 12.011 O 15.999 Na 22.99 S 32.06 >;
Line 2,945 ⟶ 3,368:
}
molar_mass($_) for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3></
{{out}}
<pre> 1.008 H1 H
Line 2,953 ⟶ 3,376:
84.162 C6H12 C6H12
186.295 C11H22O2 COOH(C(CH3)2)3CH3</pre>
=={{header|Phix}}==
A simple hand-written single-pass formula parser and evaluator in one.<br>
Line 2,959 ⟶ 3,381:
Also note that initially it all worked absolutely fine with the default precision (ie "%g" instead of "%.12g"),
and that the higher precision expected value for Na2SO4 also works just fine at both printing precisions.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">elements</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- (eg "H" -> 1.008)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">multiplier</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">formula</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">fdx</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- check for a trailing number, or return 1</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fdx</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">formula</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">formula</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'1'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'9'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">-</span><span style="color: #008000;">'0'</span>
<span style="color: #000000;">fdx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">fdx</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">formula</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">formula</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #008000;">'0'</span> <span style="color: #008080;">or</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #008000;">'9'</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">-</span><span style="color: #008000;">'0'</span>
<span style="color: #000000;">fdx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">formula</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">expected</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- (for parenthesis handling)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">sdx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fdx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">fdx</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">formula</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">formula</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'A'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'Z'</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- All elements start with capital, rest lower</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fend</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">fdx</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">fend</span><span style="color: #0000FF;"><</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">formula</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">formula</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fend</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #008000;">'a'</span> <span style="color: #008080;">or</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #008000;">'z'</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">fend</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">element</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">formula</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">..</span><span style="color: #000000;">fend</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">mass</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">element</span><span style="color: #0000FF;">,</span><span style="color: #000000;">elements</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">mass</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- missing?</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">formula</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fend</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">stack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">sdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">mass</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'('</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">sdx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">stack</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">fdx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">')'</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">formula</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">sdx</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">stack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">sdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">stack</span><span style="color: #0000FF;">[$]*</span><span style="color: #000000;">n</span>
<span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">sdx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">else</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- unknown?</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sdx</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- unbalanced brackets?</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span> <span style="color: #000000;">formula</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" ("</span><span style="color: #0000FF;">&</span><span style="color: #000000;">name</span><span style="color: #0000FF;">&</span><span style="color: #008000;">")"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000080;font-style:italic;">-- string res = sprintf("%
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%.12g"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">stack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]),</span>
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%.12g"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">expected</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">e</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" *** ERROR: expected "</span><span style="color: #0000FF;">&</span><span style="color: #000000;">e</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%26s = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">formula</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000080;font-style:italic;">-- (following clipped for brevity, works fine with whole table from task description pasted in)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">etext</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"""
C,12.011
Na,22.98976928
S,32.06
Cl,35.45
Uue,315"""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">etext</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">element</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">mass</span>
<span style="color: #0000FF;">{{</span><span style="color: #000000;">element</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mass</span><span style="color: #0000FF;">}}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">etext</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"%s,%f"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">element</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mass</span><span style="color: #0000FF;">,</span><span style="color: #000000;">elements</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"H"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hydrogen"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.008</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"H2"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hydrogen gas"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2.016</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"H2O"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Water"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">18.015</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"H2O2"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hydrogen peroxide"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">34.014</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"(HO)2"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hydrogen peroxide"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">34.014</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--molar_mass("Na2SO4","Sodium sulfate",142.036) -- (fine for "%g")</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Na2SO4"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Sodium sulfate"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">142.03553856</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- """</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"C6H12"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Cyclohexane"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">84.162</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"COOH(C(CH3)2)3CH3"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">186.295</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"C6H4O2(OH)4"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Vitamin C"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">176.124</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"C27H46O"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Cholesterol"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">386.664</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Uue"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Ununennium"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">315</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">molar_mass</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"UueCl"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">350.45</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,062 ⟶ 3,490:
UueCl = 350.45
</pre>
=={{header|Python}}==
{{trans|Julia}}
<
ATOMIC_MASS = {"H":1.008, "C":12.011, "O":15.999, "Na":22.98976928, "S":32.06, "Uue":315}
Line 3,080 ⟶ 3,507:
return print("Atomic mass {:17s} {} {:7.3f}".format(nazwa,'\t',round(eval(s),3)))
</syntaxhighlight>
{{out}}
<pre>Atomic mass H 1.008
Line 3,093 ⟶ 3,520:
Atomic mass C27H46O 386.664
Atomic mass Uue 315.000</pre>
=={{header|Racket}}==
<
(define table '([H 1.008]
Line 3,136 ⟶ 3,562:
(printf "~a: ~a\n"
(~a test #:align 'right #:min-width 20)
(~r (calc test) #:precision 3)))</
{{out}}
Line 3,152 ⟶ 3,578:
Uue: 315
</pre>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
H => 1.008 , Fe => 55.845 , Te => 127.60 , Ir => 192.217 ,
He => 4.002602 , Co => 58.933194 , I => 126.90447 , Pt => 195.084 ,
Line 3,204 ⟶ 3,629:
return $/.made.[0];
}
say .&molar_mass.fmt('%7.3f '), $_ for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>;</
{{Out}}
<pre> 1.008 H
Line 3,212 ⟶ 3,637:
84.162 C6H12
186.295 COOH(C(CH3)2)3CH3</pre>
=={{header|REXX}}==
This REXX version has some basic error checking to catch malformed chemical formulas.
Line 3,226 ⟶ 3,650:
roentgenium (Rg), copernicium (Cn), nihoniym (Nh), flerovium (Fl), moscovium (Mc),
livermorium (Lv), tennessine (Ts), oganesson (Og)
<
numeric digits 30 /*ensure enough decimal digits for mass*/
/*─────────── [↓] table of known elements (+2 more) with their atomic mass ────────────*/
Line 3,306 ⟶ 3,730:
do i=1 until \datatype(q, 'W'); q= substr(z, k+i, 1)
if datatype(q, 'W') then n= n || q /*is a digit?*/
end /*i*/; return n</
{{out|output|text= when using the default inputs:}}
<pre>
Line 3,324 ⟶ 3,748:
Mg3Si4O10(OH)2 {talc} 379.26568
</pre>
=={{header|Ruby}}==
{{trans|D}}
<
"H" => 1.008,
"He" => 4.002602,
Line 3,505 ⟶ 3,928:
end
main()</
{{out}}
<pre> H -> 1.008
Line 3,518 ⟶ 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}}==
<
struct Chem {
Line 3,790 ⟶ 4,249:
print("\(mol) => \(fmt(mass))")
}</
{{out}}
Line 3,805 ⟶ 4,264:
C27H46O => 386.664
Uue => 315.000</pre>
=={{header|VBA}}==
<
Enum ParsingStateCode
Line 3,980 ⟶ 4,438:
masses.Add 299, "Ubn"
masses.Add 315, "Uue"
End Sub</
{{out}}
Line 3,994 ⟶ 4,452:
C27H46O 386,664
Uue 315</pre>
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Dim atomicMass As New Dictionary(Of String, Double) From {
Line 4,181 ⟶ 4,638:
End Sub
End Module</
{{out}}
<pre> H -> 1.008
Line 4,194 ⟶ 4,651:
C27H46O -> 386.664
Uue -> 315.000</pre>
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
<
import "./str" for Char, Str
var atomicMass = {
Line 4,373 ⟶ 4,829:
for (molecule in molecules) {
var mass = evaluate.call(replaceParens.call(molecule))
}</
{{out}}
Line 4,393 ⟶ 4,849:
=={{header|zkl}}==
Really bad error checking
<
while(span:=str.span("(",")",False)){ // get inner most () group
group:=str[span.xplode()]; // (CH3)
Line 4,412 ⟶ 4,868:
}
ms.reduce('+);
}</
<
"Ac",227.000000, "Ag",107.868200, "Al", 26.981538, "Am",243.000000, "Ar", 39.948000,
"As", 74.921595, "At",210.000000, "Au",196.966569, "B" , 10.810000, "Ba",137.327000,
Line 4,441 ⟶ 4,897:
.concat("|","(",")([1-9]*)") )
: RegExp(_);
}();</
<
{ println(cstr," --> ",molarMass(cstr)) }</
{{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,453 ⟶ 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.
|