Tutorial 03

Previous Table of contents Next

Description

Tutorial03 introduces custom types.

Custom types are specified similar to sentences, but

In this particular example, using a custom type for the filter size doesn't provide any advantage. In general, one would use custom types to

This will be demonstrated in subsequent tutorials.

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();

      // Create a custom type 'filter-size'
      parser.defineType(
        // The name of the type:
        "filter-size",

        // The pattern to parse (i.e. a floating point number, followed by the literal " pixel(s)".
        "{stddev:float} pixel(s)",

        // An Evaluator, which in this case just returns the parsed standard deviation as a Double.
        // In principle, a custom type can evaluate to any object
        pn => pn.evaluate("stddev"));
      
      // Custom types can then be used to define other custom types, or to define sentences
      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;
        });

      new nlScript.ACEditor(parser, document.getElementById("nls-container"));
    </script>
  </body>
</html>

Demo

The result