Examples

Skip to end of metadata
Go to start of metadata

This page collects (in an unorganized manner) a number of mantra examples. See Examples tar for more.

The obligatory "hello world":

Iterate over and print the characters of a string:

Define a dict and look up a value:

You can iterate over ranges of a list or a subset of indexes without making a list copy:

emits:

List filtering:

List comprehension that does same thing:

Define a field:

and some overloaded methods

Static methods and fields and constants (U.x, U.HEIGHT, and U.bar() are all statically resolvable--useful and efficient):

Here's an actor that reads from stdin and writes lines (minus \n) to stdout.

Then you can launch an instance of Lines as an actor (in a separate thread) and pipe to another actor implicitly created from a closure. The input to the actor gets passed as the parameter and the output is the return value:

Given file:

the code emits:

because all actors read from in and write to out, whatever they are set to. They start as stdin and stdout, but the pipeline overrides them temporarily. The last actor still has out==stdout.

The Actor entity is a "mixin" that acts like an abstract base class:

You can also redirect the stream to a list:

emits:

A simple grep actor:

Sample usage: find parrt's consumption and split before grep showing it's still an object after passing through grep:

emits 3.

Some rudimentary OS support. Default stream is stdout from OS.system():

Document word frequency histogram:

An alternative way:

Closures are amazing. Here is the string.trim() method:

The same closure is used to get the index of first non whitespace moving from left to right and right to left. awesome. The closure precondition only executes "break i" when it sees a non whitespace char. The i variable is the implicitly-defined loop variable.

Accessing POJOs

It's easy to access any plain old Java object (POJO) using mantra. Just import the class using import java xxx; and then refer to it like any mantra class:

or

Here is a POJO:

To access all of this, check out the following capabilities:

Labels: