I asked here: https://stackoverflow.com/questions/36385548/how-to-programmatically-construct-a-lambda-in-java-8 but I wanted to know if there are alternatives to construct lambdas in clojure.
For the use case, I'm attempting to wrap the rethinkdb library: http://www.rethinkdb.com/api/java/#map
I may be wrong, but in the rethinkdb driver, somehow the lambdas are compiled into ast syntax that are converted to js and sent to the database. I believe I need to somehow explicitly create a lambda. http://www.rethinkdb.com/blog/lambda-functions/
so this quesion How to implement lambda as a function called "lambda" in Clojure? only shows how to use a function, not a lambda.
Lambdas are just a syntax sugar, like clojure macros. You can NOT use macros in java, or the "lambda syntax" of java in clojure. But you can create in clojure the object that the java lambda syntax creates.
That is, in java the lambda syntax creates an object that implements the interface according to the type in the method. That interface has a single non-default and non-static method.
If you want to construct a "java lambda" in clojure, what you really need to do is create an object implementing that interface.
Functional interface:
https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html
How you see the lambdas as an argument:
How do I define a method which takes a lambda as a parameter in Java 8?
Related
Now that Java 8 was officially released here: http://www.oracle.com/technetwork/java/javase/downloads/index.html
Does anyone know if we can instantiate java-lambdas or call them from JNI? There's lots of documentation for using Lambdas and all the new features in Java but nothing for JNI :S
Lambda expressions are a compile-time Java language level artifact. The Java compiler will compile the expression into a synthetic method and generate the code necessary to create an instance of the functional interface whose single abstract method will invoke the method.
Since JNI is a runtime interface there is no such thing than a lambda expression from the JNI’s point of view. There are only JRE generated implementations of functional interfaces flying around which will execute pre-built methods. They may be created in order to implement a lambda expression, a method reference, or just created manually as the creation facility is part of the public JRE API.
“Calling a lambda” is quite simple then as “calling a lambda” means invoking the single abstract interface method of the functional interface on such a generated instance. There’s no need for any special JNI function just like there is no need for special Java language features to call that method.
What JNI could do about generating a lambda is telling the JRE to generate a functional interface implementation that will invoke a specified method. If that target method is the synthetic method generated by a Java compiler for a lambda expression, you have created a lambda via JNI then. Otherwise the generated instance will just behave like a method reference to the target method.
This answer shows how such an instance can be generated using pure Java code. Most of it consists of ordinary method calls which can be invoked by JNI as well. The only tricky part is invoking the factory method represented by the MethodHandle returned by the CallSite. Since invoke and invokeExact cannot be called by JNI you have to invoke invokeWithArguments for the final step of the creation.
To summarize the creation procedure, it is all centered about the method LambdaMetafactory.metafactory which is normally used as a bootstrap method for an invokedynamic instruction but which might be invoked like an ordinary method as well, including via JNI. It’s documentation as well as it’s class documentation is quite comprehensive.
Note that this is not even an entirely new thing. A limited predecessor already exists in Java 7.
Background:
I have a Framework where I work on Objects. Up till now I created Objects in the framework with a default constructor. Now I want to introduce some customization on creation of the Objects. I decided it would be nice to allow to pass a factory into the Framework. I call it Provider, I will explain why below.
The only thing I expect in the Framework is to have a thing that will behave something like this
template< typename Provider >
void Framework::make_objects( Provider obj_provider)
{
Object obj = obj_provider();
}
I would like Provider to be anything that is callable, and returns an Object to be passed. E.g:
Factory factory;
framework.make_objects( factory.make_object ); // [1] a Factory method
framework.make_objects( []() { return Object(); } ); // [2] lambda
framework.make_objects( function_that_spits_Object ); // [3] a simple function
I call Provider a provider, and not a factory, because it is more of just a method of a factory.
Problem:
I cannot figure out a way with a simple front-end interface to pass and possibly store any kind of callable object (with a given signature). Is it possible?
What I tried:
I tried std::function, and got it to work, but gets really ugly when I want to provide Objects using a Factory method because it is overloaded, and a member method. So I need to bind factory instance to an overloaded member method. Possible but really ugly from the user side.
I think a template similar to the one Background example, would work, but it would be extremely nice to be able to store and pass the Provider. And I couldn't figure out how the template should be written to allow that.
I know that I can resolve my background/original problem, I could accept a whole Factory in the Framework, and write a constructor that would accept std::function and wrap it, so the function-type providers would implicitly get converted to Factory.
However my question for here is, is this possible to implement, to accept and store any kind of callable object, so I can just use provider() any where in the framework whenever I need a new object. This is the technical issue I am interested in here.
You can just put the member call inside the lambda, e.g. [factory] { return factory.make_object(); }. std::function is the solution here.
The problem that binding member functions sucks has nothing to do with what you're going to do with the result- there's no class or type you can use that can solve the problem of producing a wrappable function object in the first place. The syntax of f(factory.make_object) is impossible to support for any type.
Just use a lambda to wrap the member function and use std::function.
I need to somehow tag certain Clojure functions as "special" so that Java code could recognize them as such using reflection. I've tried to add an annotation to a function, but apparently that's not supported. I've tried to reify an interface extending IFn (so that the Java code could recognize the function object), but that's no good because Clojure doesn't directly use the reified method as the code implementing invoke, but rather an indirect call to an Afunction object that's actually implementing the method (I need to tag the actual invoke method with the actual function code).
Any ideas?
EDIT: even tagging in a way that could be accessed with the ASM library (rather than regular reflection) would be fine, but I need to somehow tag the actual AFunction object or the invoke method. Also, I can't access the actual AFunction object -- I need the tag to be visible on the class.
You can use clojure meta-data feature which allows meta data (a map) to be attached to any object that implements IMeta interface (which turns out to be every object as IObj extends IMeta and every object extend IObj)
Now there are 2 options.
1) You can attach the meta data to a var (the var points to the actual IFn object)
(defn hello {:name "hello"} [] 10)
and on Java side you get hold of the var hello and use IMeta methods to get the meta data and detect if your specific meta data is there or not.
The problem with this may be that your Java code access/handle IFn objects directly rather than their vars (ex: Anonymous functions), to solve this try the 2nd option.
2) Attach the meta data to the function object itself:
(def hello (with-meta (fn [] 10) {:name "hello"}))
You cannot use defn as that attach meta data to the var. The above sample code attach the meta data to the function object itself. On Java side, typecase the function object to IMeta and do the check.
The above code can be made a bit more defn likish with a help of a macro which is left as an exercise :)
It turns out that if you enclose the function body with a let statement containing a local definition, that variable name will appear in the method's local table in the class file. A bit cumbersome, though. Still looking for a better way.
For the purposes of interoperability with Java, I need a class that has a nullary constructor that performs initialization.
Objects of this class need to have something resembling mutable java fields (namely, the object represents the backend of a game, and needs to keep game state).
deftype does everything I want to do except provide a nullary constructor (since I'm creating a class with fields).
I don't need the fields to be publicly readable, so I can think of 4 solutions:
Use gen-class; I don't want to do this if I can avoid it.
Somehow encoding private member variables outside of the knowledge of deftype; I've been told this can't be done.
Writing a modified deftype that also creates a nullary constructor; frankly I don't know clojure well enough for this.
Taking the class created by deftype and somehow adding a new constructor to it.
At the end of this, I need to have a Java class, since I will be handing it off to Java code that will be making a new object from the class.
Are any of the solutions I suggested (or any that I haven't thought of) other than using gen-class viable?
There's absolutely no shame in, where appropriate, writing a dash of Java if your Java interop requirements are simultaneously specific and unshakable. You could write a Java class with a single static factory method that returns an instance of the deftype class and that does whatever initialization/setup you need.
Alternatively, you can write a nullary factory function in Clojure, and call that directly from Java all day long.
In any case, neither deftype nor defrecord are intended to be (or will they ever be) fully-featured interop facilities. gen-class certainly comes the closest, which is why it's been recommended.
I'd suggest just writing the object in Java - for Java-like objects with mutable fields it will probably be more elegant, understandable and practical.
I've generally had pretty good results mixing Java and Clojure code in projects. This seems like one of those cases where this might be appropriate. The interoperability is so good that you barely have any extra complexity.
BTW - I'm assuming that you need a nullary constructor to meet the requirements of some persistence library or something similar? It seems like an odd requirement otherwise. If this is the case then you may find it makes sense to rethink your persistence strategy..... arbitrary restrictions like this always seem like a bit of a code smell to me.
What is mean by delegates in c++, does sort function in c/c++ which takes a compare function/functor as last parameter is a form of delegate?
"delegate" is not really a part of the C++ terminology. In C# it's something like a glorified function pointer which can store the address of an object as well to invoke member functions. You can certainly write something like this in C++ as a small library feature. Or even more generic: Combine boost::bind<> with boost::function<>.
In C++ we use the term "function object". A function object is anything (including function pointers) that is "callable" via the function call operator().
std::sort takes a "predicate" which is a special function object that doesn't modify its arguments and returns a boolean value.
Callback functions in C++ can be (loosely) referred as a form of delegates ( though delegate term is not used for this). The callback functions use Pointers to Functions to pass them as parameters to other functions.
But delegates in C# is more advanced compared to callback functions in C++.
To delegate work means to share the work load with others. In real life, if you were to delegate your task, ie if you are a manager, you would be sharing your work expecting others to complete a task without you having to know how.
The concept is the same in C++ and any other languages having the capability of delegates. In C you could see this as a delegate:
int calculate(int (*func)(int c), int a, int b)
Because you are expected to send a pointer, to another function which will compute some work for you. I recently wrote a blog post on function pointers in Python and C, check it out, you might find it helpfull. This might not be the "traditional" way to delegate work in C or C++, but then again, the termonoligy says i am a bit right.
Delegation is mostly used as a way to pass functions to functionality embedded in a class (pimpl, aggregation, private inheritance). They are mainly (inlined) functions of one line, calling functions of member-classes. As far as I know, it has nothing to do with C#'s delegates.
In this sense, a function-pointer as used in qsort is not a delegate, but a callback in which framework modules can be extended by user-software as in the Hollywood principle.
Delegate: An object that acts like a multi-function pointer with a subscription system. It really simplifies the use of static or 'object' member function pointers for callback notifications and event handling.
This link explains Delegates in a lucid manner or you may also refer to the MSDN link.