Chemical calculator: Difference between revisions

Content added Content deleted
(Haskell version.)
m (syntax highlighting fixup automation)
Line 136: Line 136:


;Examples:
;Examples:
<lang python>assert 1.008 == molar_mass('H') # hydrogen
<syntaxhighlight lang=python>assert 1.008 == molar_mass('H') # hydrogen
assert 2.016 == molar_mass('H2') # hydrogen gas
assert 2.016 == molar_mass('H2') # hydrogen gas
assert 18.015 == molar_mass('H2O') # water
assert 18.015 == molar_mass('H2O') # water
Line 146: Line 146:
assert 176.124 == molar_mass('C6H4O2(OH)4') # vitamin C
assert 176.124 == molar_mass('C6H4O2(OH)4') # vitamin C
assert 386.664 == molar_mass('C27H46O') # cholesterol
assert 386.664 == molar_mass('C27H46O') # cholesterol
assert 315 == molar_mass('Uue') # ununennium</lang>
assert 315 == molar_mass('Uue') # ununennium</syntaxhighlight>




Line 156: Line 156:
Algol W has fixed length strings and no regular expressions, this parses the molecule with a simple recursive descent parser.<br>
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.
Some error checking is included.
<lang algolw>begin
<syntaxhighlight lang=algolw>begin
% calculates the molar mass of the specified molecule %
% calculates the molar mass of the specified molecule %
real procedure molar_mass ( string(256) value molecule ) ; begin
real procedure molar_mass ( string(256) value molecule ) ; begin
Line 303: Line 303:
test( 186.29499999999996, "COOH(C(CH3)2)3CH3" ); test( 350.45, "UueCl" );
test( 186.29499999999996, "COOH(C(CH3)2)3CH3" ); test( 350.45, "UueCl" );
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 316: Line 316:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>test := ["H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O"
<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"]
, "Uue", "C6H4O2(O)H)4", "X2O"]
for i, str in test
for i, str in test
Line 355: Line 355:
}
}
return str " > " sum
return str " > " sum
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>H > H > 1.008000
<pre>H > H > 1.008000
Line 372: Line 372:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 635: Line 635:
dic = NULL;
dic = NULL;
return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 651: Line 651:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{trans|D}}
{{trans|D}}
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 841: Line 841:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 857: Line 857:
=={{header|C++}}==
=={{header|C++}}==
{{trans|C#}}
{{trans|C#}}
<lang cpp>#include <iomanip>
<syntaxhighlight lang=cpp>#include <iomanip>
#include <iostream>
#include <iostream>
#include <map>
#include <map>
Line 1,054: Line 1,054:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 1,070: Line 1,070:
=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
===No Regular Expression===
===No Regular Expression===
<lang coffeescript>ATOMIC_MASS = {H:1.008,C:12.011,O:15.999,Na:22.98976928,S:32.06,Uue:315}
<syntaxhighlight lang=coffeescript>ATOMIC_MASS = {H:1.008,C:12.011,O:15.999,Na:22.98976928,S:32.06,Uue:315}


molar_mass = (s) ->
molar_mass = (s) ->
Line 1,101: Line 1,101:
assert 176.124, molar_mass 'C6H4O2(OH)4' # Vitamin C
assert 176.124, molar_mass 'C6H4O2(OH)4' # Vitamin C
assert 386.664, molar_mass 'C27H46O' # Cholesterol
assert 386.664, molar_mass 'C27H46O' # Cholesterol
assert 315, molar_mass 'Uue'</lang>
assert 315, molar_mass 'Uue'</syntaxhighlight>


===Regular Expression===
===Regular Expression===
{{trans|Julia}}
{{trans|Julia}}
<lang coffeescript>ATOMIC_MASS = {H:1.008,C:12.011,O:15.999,Na:22.98976928,S:32.06,Uue:315}
<syntaxhighlight lang=coffeescript>ATOMIC_MASS = {H:1.008,C:12.011,O:15.999,Na:22.98976928,S:32.06,Uue:315}


mul = (match, p1, offset, string) -> '*' + p1
mul = (match, p1, offset, string) -> '*' + p1
Line 1,127: Line 1,127:
assert 176.124, molar_mass('C6H4O2(OH)4') # Vitamin C
assert 176.124, molar_mass('C6H4O2(OH)4') # Vitamin C
assert 386.664, molar_mass('C27H46O') # Cholesterol
assert 386.664, molar_mass('C27H46O') # Cholesterol
assert 315, molar_mass('Uue')</lang>
assert 315, molar_mass('Uue')</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
{{trans|Go}}
{{trans|Go}}
<lang d>import std.array;
<syntaxhighlight lang=d>import std.array;
import std.conv;
import std.conv;
import std.format;
import std.format;
Line 1,312: Line 1,312:
}
}
writeln(atomicMass);
writeln(atomicMass);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 1,328: Line 1,328:
=={{header|Delphi}}==
=={{header|Delphi}}==
{{trans|Go}}
{{trans|Go}}
<lang Delphi>
<syntaxhighlight lang=Delphi>
program ChemicalCalculator;
program ChemicalCalculator;


Line 1,478: Line 1,478:
readln;
readln;
end.
end.
</syntaxhighlight>
</lang>
Include file with Atomic Mass Constants ('''AtomicMass.inc''').
Include file with Atomic Mass Constants ('''AtomicMass.inc''').
<lang Delphi>
<syntaxhighlight lang=Delphi>
const
const
ATOMIC_MASS_SIZE = 101;
ATOMIC_MASS_SIZE = 101;
Line 1,506: Line 1,506:
226, 227, 232.0377, 231.03588, 238.02891, 237, 244, 243, 247, 247, 251, 252,
226, 227, 232.0377, 231.03588, 238.02891, 237, 244, 243, 247, 247, 251, 252,
257, 315, 299);
257, 315, 299);
</syntaxhighlight>
</lang>




Line 1,512: Line 1,512:
=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.98}}
{{works with|Factor|0.98}}
<lang factor>USING: assocs compiler.units definitions grouping infix.parser
<syntaxhighlight lang=factor>USING: assocs compiler.units definitions grouping infix.parser
infix.private kernel math.functions math.parser multiline
infix.private kernel math.functions math.parser multiline
peg.ebnf qw sequences splitting strings words words.constant ;
peg.ebnf qw sequences splitting strings words words.constant ;
Line 1,596: Line 1,596:
} [ molar-mass 1e-5 approx-assert= ] assoc-each ;
} [ molar-mass 1e-5 approx-assert= ] assoc-each ;


MAIN: chemical-calculator-demo</lang>
MAIN: chemical-calculator-demo</syntaxhighlight>


No assertion errors.
No assertion errors.
Line 1,612: Line 1,612:
=={{header|Go}}==
=={{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.
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.
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 1,790: Line 1,790:
fmt.Printf("%17s -> %7.3f\n", molecule, mass)
fmt.Printf("%17s -> %7.3f\n", molecule, mass)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,809: Line 1,809:
=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Java}}
{{trans|Java}}
<lang groovy>import java.util.regex.Pattern
<syntaxhighlight lang=groovy>import java.util.regex.Pattern


class ChemicalCalculator {
class ChemicalCalculator {
Line 1,987: Line 1,987:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 2,003: Line 2,003:
=={{header|Haskell}}==
=={{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.
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.
<lang haskell>import Control.Monad (forM_)
<syntaxhighlight lang=haskell>import Control.Monad (forM_)
import Control.Monad.Reader (Reader, ask, runReader)
import Control.Monad.Reader (Reader, ask, runReader)
import Data.Bifunctor (first)
import Data.Bifunctor (first)
Line 2,066: Line 2,066:
Left err -> printf "\n%s" err
Left err -> printf "\n%s" err
Right mass -> printf " %.4f\n" mass
Right mass -> printf " %.4f\n" mass
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,090: Line 2,090:
=={{header|Java}}==
=={{header|Java}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang java>import java.util.HashMap;
<syntaxhighlight lang=java>import java.util.HashMap;
import java.util.List;
import java.util.List;
import java.util.Map;
import java.util.Map;
Line 2,271: Line 2,271:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 2,286: Line 2,286:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>
<syntaxhighlight lang=javascript>
const MASSES = {
const MASSES = {
C: 12.011,
C: 12.011,
Line 2,318: Line 2,318:
for (let i = 0; i < formulae.length; i++)
for (let i = 0; i < formulae.length; i++)
console.log(`${getSubNums(formulae[i])}: ${getMolarMass(formulae[i]).toPrecision(3)}`);
console.log(`${getSubNums(formulae[i])}: ${getMolarMass(formulae[i]).toPrecision(3)}`);
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,362: Line 2,362:


'''The PEG grammar'''
'''The PEG grammar'''
<lang jq>def Element:
<syntaxhighlight lang=jq>def Element:
parse("(?<e>^[A-Z][a-z]*)"); # greedy
parse("(?<e>^[A-Z][a-z]*)"); # greedy


Line 2,378: Line 2,378:
(plus(EN) | Parenthesized | Formula)
(plus(EN) | Parenthesized | Formula)
// (plus(EN) | optional(Parenthesized))
// (plus(EN) | optional(Parenthesized))
// (Parenthesized | optional(Formula)) ;</lang>
// (Parenthesized | optional(Formula)) ;</syntaxhighlight>
'''Evaluation of the parsed expression'''
'''Evaluation of the parsed expression'''


Line 2,384: Line 2,384:


'''The task expressed in terms of assertions'''
'''The task expressed in terms of assertions'''
<lang># A "debug" statement has been retained so that the parsed chemical formula can be seen.
<syntaxhighlight lang=text># A "debug" statement has been retained so that the parsed chemical formula can be seen.
def molar_mass(formula):
def molar_mass(formula):
{remainder: formula} | Formula | .result | debug | eval;
{remainder: formula} | Formula | .result | debug | eval;
Line 2,403: Line 2,403:
assert( 386.664; molar_mass("C27H46O")), # cholesterol
assert( 386.664; molar_mass("C27H46O")), # cholesterol
assert( 315 ; molar_mass("Uue")) # ununennium
assert( 315 ; molar_mass("Uue")) # ununennium
;</lang>
;</syntaxhighlight>
{{out}}
{{out}}
As mentioned above, a "debug" statement has been retained so that the parsed chemical formula can be seen.
As mentioned above, a "debug" statement has been retained so that the parsed chemical formula can be seen.
Line 2,422: Line 2,422:
=={{header|Julia}}==
=={{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.
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.
<lang julia>const H = 1.008
<syntaxhighlight lang=julia>const H = 1.008
const He = 4.002602
const He = 4.002602
const Li = 6.94
const Li = 6.94
Line 2,535: Line 2,535:
@assert 84.162 == molar_mass("C6H12")
@assert 84.162 == molar_mass("C6H12")
@assert 186.29500000000002 == molar_mass("COOH(C(CH3)2)3CH3")
@assert 186.29500000000002 == molar_mass("COOH(C(CH3)2)3CH3")
</syntaxhighlight>
</lang>
No assertion errors.
No assertion errors.


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|D}}
{{trans|D}}
<lang scala>var atomicMass = mutableMapOf(
<syntaxhighlight lang=scala>var atomicMass = mutableMapOf(
"H" to 1.008,
"H" to 1.008,
"He" to 4.002602,
"He" to 4.002602,
Line 2,714: Line 2,714:
println("$moleStr -> $massStr")
println("$moleStr -> $massStr")
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 2,730: Line 2,730:
=={{header|Lua}}==
=={{header|Lua}}==
{{trans|C#}}
{{trans|C#}}
<lang lua>atomicMass = {
<syntaxhighlight lang=lua>atomicMass = {
["H"] = 1.008,
["H"] = 1.008,
["He"] = 4.002602,
["He"] = 4.002602,
Line 2,907: Line 2,907:
local mass = evaluate(replaceParens(molecule))
local mass = evaluate(replaceParens(molecule))
print(string.format("%17s -> %7.3f", molecule, mass))
print(string.format("%17s -> %7.3f", molecule, mass))
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 2,925: Line 2,925:
* Also, seqs can't contain mixed types.
* Also, seqs can't contain mixed types.


<lang python>#? replace(sub = "\t", by = " ")
<syntaxhighlight lang=python>#? replace(sub = "\t", by = " ")


import tables, strutils, sequtils, math
import tables, strutils, sequtils, math
Line 3,036: Line 3,036:
assert 176.124 == molar_mass "C6H4O2(OH)4" # Vitamin C
assert 176.124 == molar_mass "C6H4O2(OH)4" # Vitamin C
assert 386.664 == molar_mass "C27H46O" # Cholesterol
assert 386.664 == molar_mass "C27H46O" # Cholesterol
assert 315 == molar_mass "Uue"</lang>
assert 315 == molar_mass "Uue"</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
===Grammar===
===Grammar===
<lang perl>use strict;
<syntaxhighlight lang=perl>use strict;
use warnings;
use warnings;
use List::Util;
use List::Util;
Line 3,060: Line 3,060:
for (<H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>) {
for (<H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>) {
printf "%7.3f %s\n", $g->weight($_), $_
printf "%7.3f %s\n", $g->weight($_), $_
}</lang>
}</syntaxhighlight>


===Regular Expression===
===Regular Expression===
<lang perl>use strict;
<syntaxhighlight lang=perl>use strict;
use warnings;
use warnings;
my %atomic_weight = < H 1.008 C 12.011 O 15.999 Na 22.99 S 32.06 >;
my %atomic_weight = < H 1.008 C 12.011 O 15.999 Na 22.99 S 32.06 >;
Line 3,088: Line 3,088:
}
}


molar_mass($_) for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3></lang>
molar_mass($_) for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3></syntaxhighlight>
{{out}}
{{out}}
<pre> 1.008 H1 H
<pre> 1.008 H1 H
Line 3,102: Line 3,102:
Also note that initially it all worked absolutely fine with the default precision (ie "%g" instead of "%.12g"),
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.
and that the higher precision expected value for Na2SO4 also works just fine at both printing precisions.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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" -&gt; 1.008)</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" -&gt; 1.008)</span>
Line 3,195: Line 3,195:
<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;">"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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,214: Line 3,214:
=={{header|Python}}==
=={{header|Python}}==
{{trans|Julia}}
{{trans|Julia}}
<lang python>import re
<syntaxhighlight lang=python>import re


ATOMIC_MASS = {"H":1.008, "C":12.011, "O":15.999, "Na":22.98976928, "S":32.06, "Uue":315}
ATOMIC_MASS = {"H":1.008, "C":12.011, "O":15.999, "Na":22.98976928, "S":32.06, "Uue":315}
Line 3,229: Line 3,229:
return print("Atomic mass {:17s} {} {:7.3f}".format(nazwa,'\t',round(eval(s),3)))
return print("Atomic mass {:17s} {} {:7.3f}".format(nazwa,'\t',round(eval(s),3)))


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Atomic mass H 1.008
<pre>Atomic mass H 1.008
Line 3,245: Line 3,245:
=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>#lang racket
<syntaxhighlight lang=racket>#lang racket


(define table '([H 1.008]
(define table '([H 1.008]
Line 3,285: Line 3,285:
(printf "~a: ~a\n"
(printf "~a: ~a\n"
(~a test #:align 'right #:min-width 20)
(~a test #:align 'right #:min-width 20)
(~r (calc test) #:precision 3)))</lang>
(~r (calc test) #:precision 3)))</syntaxhighlight>


{{out}}
{{out}}
Line 3,304: Line 3,304:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>my %ATOMIC_MASS =
<syntaxhighlight lang=raku line>my %ATOMIC_MASS =
H => 1.008 , Fe => 55.845 , Te => 127.60 , Ir => 192.217 ,
H => 1.008 , Fe => 55.845 , Te => 127.60 , Ir => 192.217 ,
He => 4.002602 , Co => 58.933194 , I => 126.90447 , Pt => 195.084 ,
He => 4.002602 , Co => 58.933194 , I => 126.90447 , Pt => 195.084 ,
Line 3,353: Line 3,353:
return $/.made.[0];
return $/.made.[0];
}
}
say .&molar_mass.fmt('%7.3f '), $_ for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>;</lang>
say .&molar_mass.fmt('%7.3f '), $_ for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>;</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1.008 H
<pre> 1.008 H
Line 3,375: Line 3,375:
roentgenium (Rg), copernicium (Cn), nihoniym (Nh), flerovium (Fl), moscovium (Mc),
roentgenium (Rg), copernicium (Cn), nihoniym (Nh), flerovium (Fl), moscovium (Mc),
livermorium (Lv), tennessine (Ts), oganesson (Og)
livermorium (Lv), tennessine (Ts), oganesson (Og)
<lang rexx>/*REXX program calculates the molar mass from a specified chemical formula. */
<syntaxhighlight lang=rexx>/*REXX program calculates the molar mass from a specified chemical formula. */
numeric digits 30 /*ensure enough decimal digits for mass*/
numeric digits 30 /*ensure enough decimal digits for mass*/
/*─────────── [↓] table of known elements (+2 more) with their atomic mass ────────────*/
/*─────────── [↓] table of known elements (+2 more) with their atomic mass ────────────*/
Line 3,455: Line 3,455:
do i=1 until \datatype(q, 'W'); q= substr(z, k+i, 1)
do i=1 until \datatype(q, 'W'); q= substr(z, k+i, 1)
if datatype(q, 'W') then n= n || q /*is a digit?*/
if datatype(q, 'W') then n= n || q /*is a digit?*/
end /*i*/; return n</lang>
end /*i*/; return n</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 3,476: Line 3,476:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|D}}
{{trans|D}}
<lang ruby>$atomicMass = {
<syntaxhighlight lang=ruby>$atomicMass = {
"H" => 1.008,
"H" => 1.008,
"He" => 4.002602,
"He" => 4.002602,
Line 3,654: Line 3,654:
end
end


main()</lang>
main()</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 3,670: Line 3,670:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>import Foundation
<syntaxhighlight lang=swift>import Foundation


struct Chem {
struct Chem {
Line 3,939: Line 3,939:


print("\(mol) => \(fmt(mass))")
print("\(mol) => \(fmt(mass))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,956: Line 3,956:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vba>Option Explicit
<syntaxhighlight lang=vba>Option Explicit


Enum ParsingStateCode
Enum ParsingStateCode
Line 4,129: Line 4,129:
masses.Add 299, "Ubn"
masses.Add 299, "Ubn"
masses.Add 315, "Uue"
masses.Add 315, "Uue"
End Sub</lang>
End Sub</syntaxhighlight>


{{out}}
{{out}}
Line 4,146: Line 4,146:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Module Module1
<syntaxhighlight lang=vbnet>Module Module1


Dim atomicMass As New Dictionary(Of String, Double) From {
Dim atomicMass As New Dictionary(Of String, Double) From {
Line 4,330: Line 4,330:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre> H -> 1.008
<pre> H -> 1.008
Line 4,348: Line 4,348:
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|Wren-str}}
{{libheader|Wren-str}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt
import "/str" for Char, Str
import "/str" for Char, Str


Line 4,523: Line 4,523:
var mass = evaluate.call(replaceParens.call(molecule))
var mass = evaluate.call(replaceParens.call(molecule))
System.print("%(Fmt.s(17, molecule)) -> %(Fmt.f(7, mass, 3))")
System.print("%(Fmt.s(17, molecule)) -> %(Fmt.f(7, mass, 3))")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,542: Line 4,542:
=={{header|zkl}}==
=={{header|zkl}}==
Really bad error checking
Really bad error checking
<lang zkl>fcn molarMass(str,mass=0.0){
<syntaxhighlight lang=zkl>fcn molarMass(str,mass=0.0){
while(span:=str.span("(",")",False)){ // get inner most () group
while(span:=str.span("(",")",False)){ // get inner most () group
group:=str[span.xplode()]; // (CH3)
group:=str[span.xplode()]; // (CH3)
Line 4,561: Line 4,561:
}
}
ms.reduce('+);
ms.reduce('+);
}</lang>
}</syntaxhighlight>
<lang zkl>var [const] atomicMass = Dictionary(
<syntaxhighlight lang=zkl>var [const] atomicMass = Dictionary(
"Ac",227.000000, "Ag",107.868200, "Al", 26.981538, "Am",243.000000, "Ar", 39.948000,
"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,
"As", 74.921595, "At",210.000000, "Au",196.966569, "B" , 10.810000, "Ba",137.327000,
Line 4,590: Line 4,590:
.concat("|","(",")([1-9]*)") )
.concat("|","(",")([1-9]*)") )
: RegExp(_);
: RegExp(_);
}();</lang>
}();</syntaxhighlight>
<lang zkl>foreach cstr in (T("H","H2","H2O","Na2SO4","C6H12","COOH(C(CH3)2)3CH3"))
<syntaxhighlight lang=zkl>foreach cstr in (T("H","H2","H2O","Na2SO4","C6H12","COOH(C(CH3)2)3CH3"))
{ println(cstr," --> ",molarMass(cstr)) }</lang>
{ println(cstr," --> ",molarMass(cstr)) }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>