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:

  1. We use the IO and String modules for input/output operations and string manipulation.

  2. The stringToReal() method is used to parse floating-point numbers.

  3. stringToInt() is used for parsing integers. It can handle different bases, including hexadecimal when base 16 is specified.

  4. stringToUint() is used for parsing unsigned integers.

  5. Chapel doesn’t have a direct equivalent to Go’s Atoi, but stringToInt() can be used for basic base-10 integer parsing.

  6. 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.