Number Parsing in Chapel
Chapel provides built-in modules for parsing numbers from strings. Let’s explore how to do this in Chapel.
use IO;
use String;
proc main() {
// With stringToReal, we can parse floating-point numbers
var f = "1.234".stringToReal();
writeln(f);
// For parsing integers, we can use stringToInt
var i = "123".stringToInt();
writeln(i);
// stringToInt will recognize hex-formatted numbers when
// we specify the base as 16
var d = "0x1c8".stringToInt(base=16);
writeln(d);
// For unsigned integers, we can use stringToUint
var u = "789".stringToUint();
writeln(u);
// Chapel doesn't have a direct equivalent to Go's Atoi,
// but we can use stringToInt for basic base-10 integer parsing
var k = "135".stringToInt();
writeln(k);
// Parsing functions in Chapel throw errors on bad input
try {
var _ = "wat".stringToInt();
} catch e {
writeln(e);
}
}
To run the program:
$ chpl number-parsing.chpl
$ ./number-parsing
1.234
123
456
789
135
bad integer
In this Chapel code:
We use the
IO
andString
modules for input/output operations and string manipulation.The
stringToReal()
method is used to parse floating-point numbers.stringToInt()
is used for parsing integers. It can handle different bases, including hexadecimal when base 16 is specified.stringToUint()
is used for parsing unsigned integers.Chapel doesn’t have a direct equivalent to Go’s
Atoi
, butstringToInt()
can be used for basic base-10 integer parsing.In Chapel, parsing functions throw errors on bad input, which we can catch using a try-catch block.
This example demonstrates how Chapel handles number parsing from strings, which is a common task in many programs.
Next, we’ll look at another common parsing task: URLs.