One of the best kept secrets about SPIN is its ability to define new SPARQL functions that encapsulate complex sub-queries into reusable building blocks. Normal SPIN functions are limited to whatever can be expressed in SPARQL, by means of a nested spin:body query. TopBraid has extended this idea by allowing functions with other implementations yet the same general RDF vocabulary. TopBraid users have been able to define new functions using SPARQLMotion and even JavaScript for several years.
TopBraid 4.3 adds the ability to define new SPARQL functions using SPARQL Web Pages (SWP). SWP is better known for its role in generating HTML, yet it also acts as a general expression language for procedural programming. SWP includes control elements such as ui:if/ui:else and ui:forEach and even the ability to invoke SPARQLMotion modules, and all that with a compact textual notation.
Here is an example SWP function that gets the current exchange rate between two given currencies using the currency2currency.org web service:
SWP functions look almost exactly like SPIN functions, only that they have the type ui:Function and use a ui:prototype instead of a spin:body. The prototype will be evaluated with the function arguments as pre-bound variables (shown in bold-face above). The new element ui:return can be used to return the resulting RDF node. An example call is shown below:
Instead of using ui:return, SWP functions can also simply produce any text, and the resulting text elements will be concatenated into the function result. This is illustrated in the following example:
An example call sequence is shown below:
SWP functions are a more powerful alternative to normal SPIN functions, especially if the business logic is too complex to express with SPARQL alone, if SPARQLMotion callbacks are needed, or if the function’s result consists of text that is easier constructed with SWP’s rich text generation capabilities.