Xquery: Passing functions as argument - function-pointers

I'm working on an xml project in Xquery (using Exist) and I was wondering how I could achieve the following:
I want to create a function evaluate:
evaluate(argument, function)
argument here can be anything and should be compatible with the function.
function is a reference to a function.
some examples:
evaluate(6,nextPrime) -> newtPrime(6) = 7
evaluate("text",toCaps) -> toCaps("text") = TEXT
Is this or something very similar possible in Xquery? And if so, how?
Thank you in advance!

I couldn't tell you about exist, but MarkLogic has function pointers:
xquery version "1.0-ml";
declare function local:upper($str)
{
fn:upper-case($str)
};
let $function := xdmp:function(xs:QName("local:upper"))
return xdmp:apply($function, "blah")
Evaluating this returns BLAH.

dave was right similar support for higher order functions is found in Exist.
http://en.wikibooks.org/wiki/XQuery/Higher_Order_Functions
I did not use the exist mechanisms since QName only supports string literals and I could not achieve the dynamic behaviour I needed for my application.
Instead I used this trick:
declare function moviestat:call1($name, $param){
let $query := concat($name, "($param)")
return util:eval($query)
};
note that a generic function for any number of arguments can also be made
(but was not needed in application)

Related

Swift syntax: UnsafeMutablePointers in CGPDFDocument.getVersion

Can anyone explain how I'm supposed to use the method 'getVersion' for CGPDFDocument in Swift?
Apple's documentation gives:
func getVersion(majorVersion: UnsafeMutablePointer<Int32>,
minorVersion: UnsafeMutablePointer<Int32>)
"On return, the values of the majorVersion and minorVersion parameters are set to the major and minor version numbers of the document respectively."
So I supply two variables as arguments of the function, and they get filled with the values on exit? Do they need to point to something in particular before the method is called? Why not just type them as integers, if that's what the returned values are?
You use it like this:
var major: Int32 = 0
var minor: Int32 = 0
document.getVersion(majorVersion: &major, minorVersion: &minor)
print("Version: \(major).\(minor)")
The function expects pointers, but if you pass in plain Int32 variables with the & operator, the Swift compiler is smart enough to call the function with pointers to the variables. This is documented in Using Swift with Cocoa and Objective-C: Interacting with C APIs.
The main reason the function works like this is probably that it's a very old C function that has been imported into Swift. C doesn't support tuples as return values; using pointers as in-out parameters is a way to have the function return more than one value. Arguably, it would have been a better design to define a custom struct for the return type so that the function could return the two values in a single type, but the original developers of this function apparently didn't think it was necessary — perhaps unsuprisingly, because this pattern is very common in C.

What does [parametertype[]]$Parameter mean?

I have seen PowerShell function parameters defined using the syntax param([parametertype[]]$Parameter) as well as param([parametertype]$Parameter).
Personally, I have always used the latter with (as far as I can tell) no problems. Can anyone explain what (if any) is the difference and why both are allowed and work?
[parametertype[]]$Parameter is a parametertype array of $Parameter
[parametertype]$Parameter is a $Parameter of parametertype
i.e.
> [string]$param_s = "parameter"
> [string[]]$param_a = "parameter", "param2", "param3"
> $param_s[1]
a
> $param_a[1]
param2
Note how param_s is a plain string and accesses the second position in the string when accessing index [1] compared to what's returned by param_a[1]
When used by the param keyword in a function / cmdlet definition, it just ensures the function will be passed correct data type
in powershell you don't have to define what parameter you are using but you can.
sometimes it can be handy if you want to define a parameter as [mandatory] for example.
in your example you defind an array type param[] and single type.
you can read more about Defining Parameters.

Why is this Coffeescript invalid?

I'm playing around with Coffeescript, trying to convert a JavaScript file to Coffeescript. This is valid JavaScript:
element(by.model('query.address')).sendKeys('947');
This is invalid Coffeescript:
element(by.model('query.address')).sendKeys('947')
What is invalid about the Coffeescript? Coffeelint says "unexpected BY".
CoffeeScript uses the by keyword to let you use a specific step when looping through a range.
From the documentation:
To step through a range comprehension in fixed-size chunks, use by, for example:
evens = (x for x in [0..10] by 2)
Since JavaScript doesn't use by it's valid. For CoffeeScript, try renaming the by to something else.
In response to the comment, since Protractor provides its own by global variable, one idea is to alias it via CoffeeScript's embedded JavaScript syntax (code surrounded by back-ticks), then continue using CoffeeScript and the alias throughout your code.
You'll need to test this type of code:
ptorBy = `by`
element(ptorBy.model('query.address')).sendKeys('947')
Where ptor is just my short-hand for "Protractor." This translates to the following JavaScript:
var ptorBy;
ptorBy = by;
element(ptorBy.model('query.address')).sendKeys('947');

Using LuaJ with Scala

I am attempting to use LuaJ with Scala. Most things work (actually all things work if you do them correctly!) but the simple task of setting object values has become incredibly complicated thanks to Scala's setter implementation.
Scala:
class TestObject {
var x: Int = 0
}
Lua:
function myTestFunction(testObject)
testObject.x = 3
end
If I execute the script or line containing this Lua function and pass a coerced instance of TestObject to myTestFunction this causes an error in LuaJ. LuaJ is trying to direct-write the value, and Scala requires you to go through the implicitly-defined setter (with the horrible name x_=, which is not valid Lua so even attempting to call that as a function makes your Lua not parse).
As I said, there are workarounds for this, such as defining your own setter or using the #BeanProperty markup. They just make code that should be easy to write much more complicated:
Lua:
function myTestFunction(testObject)
testObject.setX(testObject, 3)
end
Does anybody know of a way to get luaj to implicitly call the setter for such assignments? Or where I might look in the luaj source code to perhaps implement such a thing?
Thanks!
I must admit that I'm not too familiar with LuaJ, but the first thing that comes to my mind regarding your issue is to wrap the objects within proxy tables to ease interaction with the API. Depending upon what sort of needs you have, this solution may or may not be the best, but it could be a good temporary fix.
local mt = {}
function mt:__index(k)
return self.o[k] -- Define how your getters work here.
end
function mt:__newindex(k, v)
return self.o[k .. '_='](v) -- "object.k_=(v)"
end
local function proxy(o)
return setmetatable({o = o}, mt)
end
-- ...
function myTestFunction(testObject)
testObject = proxy(testObject)
testObject.x = 3
end
I believe this may be the least invasive way to solve your problem. As for modifying LuaJ's source code to better suit your needs, I had a quick look through the documentation and source code and found this, this, and this. My best guess says that line 71 of JavaInstance.java is where you'll find what you need to change, if Scala requires a different way of setting values.
f.set(m_instance, CoerceLuaToJava.coerce(value, f.getType()));
Perhaps you should use the method syntax:
testObject:setX(3)
Note the colon ':' instead of the dot '.' which can be hard to distinguish in some editors.
This has the same effect as the function call:
testObject.setX(testObject, 3)
but is more readable.
It can also be used to call static methods on classes:
luajava.bindClass("java.net.InetAddress"):getLocalHost():getHostName()
The part to the left of the ':' is evaluated once, so a statement such as
x = abc[d+e+f]:foo()
will be evaluated as if it were
local tmp = abc[d+e+f]
x = tmp.foo(tmp)

Function returning 2 types based on input in Perl. Is this a good approach?

i have designed a function which can return 2 different types based on the input parameters
ex: &Foo(12,"count") -> returns record count from DB for value 12
&Foo(12,"details") -> returns resultset from DB for value 12 in hash format
My question is is this a good approach? in C# i can do it with function overload.
Please think what part of your code gets easier by saying
Foo(12, "count")
instead of
Foo_count(12)
The only case I can think of is when the function name ("count") itself is input data. And even then do you probably want to perform some validation on that, maybe by means of a function table lookup.
Unless this is for an intermediate layer that just takes a command name and passes it on, I'd go with two separate functions.
Also, the implementation of the Foo function would look at the command name and then just split into a private function for every command anyway, right?
additionally you might consider the want to make foo return the details if you wanted a list.
return wantarray ? ($num, #details) : $num;