Glyph - Simple Programming and Code Evaluation

Turing-completeness

As of version 0.5.0, Glyph can be considered Turing-complete, as it satisfies the following requirements for Turing-completeness:

  • A conditional construct, implemented via the condition macro.
  • Variable assignment, by setting the value of snippets using the snippet: macro and of attributes using the attribute: macro.
  • (infinite) iteration implemented through the while macro or recursion, which is possible thanks to the define: macro.
  • A memory model which emulates an infinite store: there are no enforced limits on attribute/snippets allocations and number of algorithms or parameters.

Operations on integer values

Glyph can be used to perform operation on integer values (additions, subtractions and multiplications). For example, add[2|3|7] will evaluate to @12@, and multiply[add[3|7]|subtract[5|1|2]] will return 20.

As a more complex example, consider the following @factorial@ macro, which is able to calculate the factorial of a number recursively:

1def:[factorial|
2  ?[
3    eq[{{0}}|0]|1|
4    multiply[
5      {{0}} | factorial[subtract[{{0}}|1]]
6    ]
7  ]
8]

If you try executing factorial[5], it will evaluate to @120@.

Lexically-scoped attribute assignment

Snippets can be used in a similar way as variables are used in programming languages. Or better, they can be used as global variables, as they are visible from anywhere in the Glyph document. If you need something more restricted to, say, a section and all its subsections, you can define your own attributes and use them in a very similar way.

Consider the following Glyph code:

1let[
2  @:[a|bits]
3  @:[b|bobs]
4  section[
5    @title[Something more about attributes]
6Attributes are like lexically scoped variables. You can use them to store @[a] and @[b].
7  ]
8]

The let macro here only acts as a dummy macro (it does nothing really) to bind attributes using the attribute: macro (aliased by @:). Attributes can then be used anywhere within the let macro, so the content of the section reads: “Attributes are like lexically-scoped variables. You can use them to store bits and bobs”.

Note that attributes defined through the attribute: macro are… well, attributes! Feel free to use the attribute macro to access standard attributes like title, etc.

Evaluating Ruby code

For anything more complex than what described in the previous sections you can also evaluate simple ruby code snippets using the ruby macro (aliased to %), like this:

  • %[2 + 2] → 4
  • %[Time.now] → 2014-10-04 21:34:10 +0200
  • %[Glyph::VERSION] → 0.5.3.1

The scope for the code evaluation is the Kernel module, (with all inclusions required by Glyph itself).

Although it is possible to retrieve Glyph configuration settings in this way (e.g. %[cfg('document.author')]), the config macro (aliased to $) makes things slightly simpler (e.g. $[document.author]).