Johan
Johan

Reputation: 11

Recursive function returning boolean, with a for loop inside

My data is a binary tree, and will check through every child, returning true if it finds the data i want, if not, it keeps looking for it. In some way i want to return the variable @exists or something.. Well anyone might have a solution for my problem. I was thinking something like this but i couldn't get it to work! (code-snippet)

declare function local:test($id as xs:integer, $topic as xs:integer) as xs:boolean {
    let $exists := fn:false()
    for $x in ...
    return
        if .. then
            set exists to fn:true()
        else
            set exists to exists OR local:test($x,$topic)

    return @exists in some way  
};

Upvotes: 1

Views: 2489

Answers (3)

Gunther
Gunther

Reputation: 5256

This is a case for an XQuery quantified expression. Using that, your function translates to

declare function local:test($id as xs:integer, $topic as xs:integer) as xs:boolean
{
  some $x in ...
  satisfies
    if (..) then
      fn:true()
    else
      local:test($x,$topic)
};

Upvotes: 2

Shcheklein
Shcheklein

Reputation: 6349

As it was already mentioned XQuery is a functional language. You can't just set variable and return it. Your query can be though rewritten like:

declare function local:test($id as xs:integer, $topic as xs:integer) as xs:boolean {
    exists(for $x in ...
           where (: here is condition expression on $x :)
           return $x)
};

Function exists(Expr) returns true if the value of Expr is not the empty sequence; otherwise, the function returns false.

In this case exists returns true if there is $x which meets specified condition.

Upvotes: 1

Oliver Hallam
Oliver Hallam

Reputation: 4262

You cannot change the values of variables in xquery.

Is your whole function not just this:

declare function local:test($topic as xs:integer) as xs:boolean {
     ... OR local:test($topic/...)
};

Upvotes: 0

Related Questions