Tutorial 05

Previous Table of contents Next

Description

Tutorial05 demonstrates how to provide multiple definitions for a type. The type 'units' is first defined as the string literal "pixel(s)" and additionally as "calibrated units".

As a result, once the user hits the corresponding position during input, an autocompletion menu will be displayed to select between the two.

For details, see also

The code


<!doctype html>
<html>
  <body>
    <!-- The HTML element that will hold the editor -->
    <div id="nls-container"></div>

    <!-- The only javascript file needed for nlScript -->
    <script src="https://cdn.jsdelivr.net/npm/@nlscript/nlscript@0.3.0/dist/umd/nlScript.js"></script>

    <!-- Load the library for the actual processing -->
    <script src="preprocessing.js"></script>

    <script>
      let preprocessing = new Preprocessing("output");
      
      let parser = new nlScript.Parser();

      // 1. Define the type "units" as the string literal "pixel(s)"
      parser.defineType("units", "pixel(s)", pn => false);

      // 2. Define the type "units" as the string literal "calibrated units"
      parser.defineType("units", "calibrated units", pn => true);
      
      parser.defineType("filter-size", "{stddev:float} {units:units}", pn => {
        let stddev = pn.evaluate("stddev");

        // Note that the "units" type evaluates to a Boolean, which is true if "calibrated units" was
        // parsed, and false if "pixel(s)" was parsed
        let units = pn.evaluate("units");

        // Convert stddev to pixel units in case it was specified in calibrated units
        if(units)
          stddev /= preprocessing.getPixelWidth();
        return stddev;
      }, true);
      
      parser.defineSentence(
        "Apply Gaussian blurring with a standard deviation of {stddev:filter-size}.",
        pn => {
          let stdDev = pn.evaluate("stddev");
          preprocessing.gaussianBlur(stdDev);
          preprocessing.show("output");
          return undefined;
        });

    </script>
  </body>
</html>

Demo

The result