简体   繁体   中英

assigning an operator to a variable in xquery

is there a way to assign a numeric operator to a variable in Xquery?

I have to perform an arithmetic expression on a given pair of values depending upon a node tag.

I've managed to do this but its resulted in a lot of duplicate code. I'd like to simplify the query so that instead of:

Function for Add

Repeated if code - this calls out to other functions but is still repeated

$value1 + $value2

Function for Minus

Repeated if code

$value1 - $value2

etc for multiply, div etc

I'd like to set up a function and send a variable to it, something similar to this:

$value1 $operator $value2

Is there a simple way to do this in xquery?

thank you for your help.

If your query processor supports XQuery 3.0 , you can use function items for that:

declare function local:foo($operator, $x, $y) {
  let $result := $operator($x, $y)
  return 2 * $result
};

local:foo(...) can then be called like this:

let $plus := function($a, $b) { $a + $b },
    $mult := function($a, $b) { $a * $b }
return (
  local:foo($plus, 1, 2),
  local:foo($mult, 3, 4)
)

Why don't you use a simple if-else construct? Eg

if (repeated code says you should add) then
  $value1 + $value2
else
  $value1 - $value2

You could also simple put the repeated code in another function instead of copying the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM