FunctionDecl

Declare a user-defined function.

Top of page

Related Syntax Constructs

The following construct(s) refer to this construct:


Syntax

FunctionDecl

graphics/FunctionDecl.png

TaminoQPIInline QName Variable SequenceType SequenceType EnclosedExpr

Description

A FunctionDecl is part of a prolog. It declares a user-defined function by specifying its name, a parameter list and the optional result type. The enclosed expression is called the function body. The parameter list is enclosed in parentheses and comprises a comma-separated list of parameters with their names and optional types. The scope of the function parameters is the function body. A parameter name may appear only once in the function declaration.

The type information is optional: If a parameter is specified without a type then the default type item* is used. If the type of the result value is not specified, again item* is used. If you specify a type, you can use one of the following XQuery types as parameter or return types: all simple types, item, node, attribute, comment, document, element, processing-instruction, and text. This also means that you cannot use a user-defined type as return or parameter type.

Every function must be in a namespace, that is every declared function name must have a non-empty namespace URI. Every function name declared in a library module must be in the target namespace of the library module. However, in a main module you can declare functions for local use without defining a new namespace. For this purpose, the namespace preceded by the URI local is predeclared and bound to http://www.w3.org/2004/07/xquery-local-functions.

Function declarations may be recursive. Also, mutually recursive functions are allowed, that is, functions whose bodies reference each other.

Furthermore, you can prepend the query directive TaminoQPIInline to affect the way this function is optimized by the query processor.

Example

  • This recursive function returns the depth of the current node on the element axis.

    module namespace tree="http://www.examples.com/tree"
    declare function tree:depth($e as node()) as xs:integer
    {
    	if (not($e/*))	
    	then
    	 	1
    	else		
    		 max(for $c in $e/* return tree:depth($c)) + 1
    }

    This function declaration is part of a library module. In order to use it directly in a main module instead, drop the module declaration and use the namespace prefix "local" instead of "tree".