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:
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:
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:
A simple grep actor:
Sample usage: find parrt's consumption and split before grep showing it's still an object after passing through grep:
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.
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:
Here is a POJO:
To access all of this, check out the following capabilities: