Product SiteDocumentation Site

12.4. User-Defined Functions

You can define your own functions in the prolog.
Unlike variables, user-defined functions must be prefixed, because unprefixed functions are the builtin functions.
In the prolog of a main query, these user-defined functions must be prefixed with the predefined alias local:, both in the declaration and when called.
Remember that types are optional, and if you do not specify any, item* is assumed, both for parameters and for the return type.
Example 12.8. Some user-defined functions.
declare function local:say-hello-1($x)
{
  "Hello, " || $x || "!" 
};

declare function local:say-hello-2($x as string)
{
  "Hello, " || $x || "!"
};

declare function local:say-hello-3($x as string)
    as string
{
  "Hello, " || $x || "!"
};

local:say-hello-1("Mister Spock"),
local:say-hello-2("Mister Spock"),
local:say-hello-3("Mister Spock")
Results:
"Hello, Mister Spock!"
"Hello, Mister Spock!"
"Hello, Mister Spock!"

If you do specify types, an error is raised in case of a mismatch
Example 12.9. A type mismatch for a user-defined function (failing).
declare function local:say-hello($x as string)
{
  "Hello, " || $x || "!"
}; 

local:say-hello(1)
Error:
xs:integer can not be promoted to parameter type xs:string 
of function local:say-hello()