Clojure : type hint tower - clojure

I write sometimes java methods, especially for primitives/arrays operations and I am always stuck about how to use type hints under Clojure 1.8. I saw some threads but they are (maybe ?) outdated considering they have been posted more than 2 years ago.
I will give a basic example to illustre my point (I know this example is a bit pointless). Here i want to sum two double and to return a double.
Here is a Java method :
public static double add (double a, double b) {
return a + b;
}
Then I would like to have a Clojure wrapper :
Version 1
(defn d+ ^double
[^double a ^double b]
(Doubles/add a b))
Version 2
(defn d+ ^double
[^double a ^double b]
(Doubles/add ^double a ^double b))
Version 3
(defn d+ ^double
[^double a ^double b]
(Doubles/add (double a) (double b)))
I do not know where to put type hints and how to put them. I have the impression that (double x) is less efficient since it is a function (maybe I am wrong ?).
Then what is the difference between giving hints inside body function or outside ?
Or maybe these hints are not necessary since there is only one method in the Java class ?
I do not see the logic so generally I use version 1 or 3 (more is better ?).
Note that for this example, Clojure + is always faster

Version 1 is correct. It'll emit the following byte code:
public final class compile_inspect$d_PLUS_ extends AFunction implements DDD {
public compile_inspect$d_PLUS_() {
}
public static double invokeStatic(double a, double var2) {
return Primitives.add(a, var2);
}
public Object invoke(Object var1, Object var2) {
return new Double(invokeStatic(RT.uncheckedDoubleCast((Number)var1), RT.uncheckedDoubleCast((Number)var2)));
}
public final double invokePrim(double var1, double var3) {
return invokeStatic(var1, var3);
}
}
Where Primitives.add is just like your Doubles/add function.
If you want performance and avoid boxing you should set:
(set! *unchecked-math* :warn-on-boxed)
Also going through the Java interop reference (CTRL+F "primitive") will help.

Related

Prototype for Multiple functions in one declaration

Quick newbie question: how do I read the block of code below (it comes from the textbook Physically Based Rendering Section 12.1)? It's something that I've never seen before. Is it the prototype for three different functions of class Light (i.e. Light::nSamples, Light::LightToWorld, and Light::WorldToLight)?
(Light Interface) ≡ 606
Light(const Transform &l2w, int ns = 1)
: nSamples(max(1, ns)), LightToWorld(l2w),
WorldToLight(Inverse(l2w)) {
(Warn if light has transformation with scale)
}
You have a bunch of pseudo code mixed with c++ syntax.
(Light Interface) ≡
It means nothing, probably a comment. You even have some Unicode chars there.
The rest looks like a bad definition of a constructor of class Light
Light(const Transform &l2w, int ns = 1)
This would be the constructor with it's arguments, it's has an error as it should be Light::Light(const Transform &l2w, int ns = 1)
: nSamples(max(1, ns)), LightToWorld(l2w),
WorldToLight(Inverse(l2w))
This is instantiation of member variables and base classes.
{
(Warn if light has transformation with scale)
}
Here would go the constructor code, instead of another weird pseudocode comment.
There's a good reason you've never seen it before. This is nonsense:
(Light Interface) =
The rest, if it was written
Light::Light(const Transform & l2w, int ns - 1)
...
would be the definition of a constructor.
I'm not familiar with the book this comes from, but I'm skeptical that this sort of informality will actually be helpful.

How to store CPP classe in R object?

I want to know if there is a way to store a CPP class in a R object.
I understand that we can call CPP function in R and we can also call method of a CPP class.
But I want to manipulate the CPP class in a R object, I don't know if this is possible.
Example :
I call this code in a R Script :
dyn.load(paste("X", .Platform$dynlib.ext, sep = ""))
.C("X_main")
The function X_main :
extern "C" {
void X_main () {
X x;
}
}
in X.cpp :
X::X() { cout<<"constructor X\n"<<endl;}
Can I store an object of the class "X" in a R object ? And use method of class "X" on the object stored (after in the script) ?
Or, Can I store in the memory an object of the class X ? I want to use this object several times.
By writing converters, you can assign the components of X which map to types R also knows: integer, numeric, character, ... all as scalar or vector, and of course composites of these.
But you do not get it for free. With Rcpp and friends, we have all the wrapper -- as well as a bunch of build tools -- to make this easy:
R> library(Rcpp)
R> cppFunction("arma::mat doubleIt(arma::mat X) { return 2*X; }",
+ depends="RcppArmadillo")
R> doubleIt(matrix(1:9,3))
[,1] [,2] [,3]
[1,] 2 8 14
[2,] 4 10 16
[3,] 6 12 18
R>
There are over 900 other Rcpp questions here, almost 100 worked examples at the Rcpp Gallery site. Have a look around!
You can load a C++ class (and probably struct) within R, which saves variables within class scope. R treats C++ classed like an S4 class.
Under the hood, a pointer to a C++ object instance is passed around, so you can create an object instance in C++ and then pass it to R sharing data.
To learn how to do this, it's about 7 pages, but well worth the read, so get out a cup of coffee and checkout: Exposing C++ functions and classes with Rcpp modules by Dirk Eddelbuettel and Romain François.
An example from the pdf:
class Bar {
public:
Bar(double x_) : x(x_), nread(0), nwrite(0) {}
double get_x() {
nread++;
return x;
}
void set_x(double x_) {
nwrite++;
x = x_;
}
IntegerVector stats() const {
return IntegerVector::create(_["read"] = nread,
_["write"] = nwrite);
}
private:
double x;
int nread, nwrite;
};
RCPP_MODULE(mod_bar) {
class_<Bar>( "Bar" )
.constructor<double>()
.property( "x", &Bar::get_x, &Bar::set_x )
.method( "stats", &Bar::stats )
;
}
And in R:
Bar <- mod_bar$Bar
b <- new(Bar, 10)
b$x + b$x
b$stats()
b$x <- 10
b$stats()

Rcpp return of C/C++ Array Pointer Object

i want to write my own Datatype in C/C++.
I generated a small class like this :
#include <Rcpp.h>
using namespace Rcpp;
class Test
{
public:
int rows;
int cols;
float a[10];
Test() {};
};
RCPP_EXPOSED_CLASS( Test )
RCPP_MODULE(mod){
class_<Test>("Test")
.constructor()
.field("rows", & Test::rows )
.field("rows", & Test::cols )
// .field("a", & Test :: a)
;
}
the code is running. But now i want to get the values from a. Ive i understand the documentation correct i have to create a "as" function ? And return a NumericVector ?
I didnt understand the SEXP type, is it a pointer that is "typeless" and can be used in C/c++ and R ?
That's a lot of somewhat elementary questions.
Maybe you should not start with a module and class? How about
You could rewrite your class containing a std::vector<double> a.
You write a simple 'init()' function that assigns the class to file-local variable (usually a pointer).
You write little setter and getter functions, see Rcpp Attributes.
Once a few things are more clear more doing basics, revisit the Rcpp Modules vignette.

Multi-tier complex state machine

I'm currently trying to come up with a clean design for coding a multi-tier state machine, and so far, I haven't found the solution in articles about normal state machine usage in C++ or other.
On the very bottom of the hierarchy, we have atomic states: a, b, c, ..., x, y, z.
On top of that, there is a first tier of composite states: A, B, C, D.
Finally, on the very top, there is a final aggregate root state X.
X
A B C D
a b c d e f g h...
In contrast to the usual state machine, the lowest states are defined and determined by external factors; there are no detectable events that change them, changes are detected simply by observing.
Following an atomic state change, he first composite layer has a set of states that it could take, depending on the combination of lower states. For instance: a, b and c are "child"-states of A:
a b c - A
0 0 0 - 0
1 0 0 - 1
2 0 0 - x
2 1 0 - 2
and so on...where x is undefined.
Finally, the root state has a set of states it can take, based on the composite states - following the same logic as before.
So far, I tried a top-down approach, where the root would call into the sub-states, which in turn would call into the atomic states to update them, cascading back up.
I also tried a bottom-up approach, where the atomic states would update and call up into the sub-states, which in turn would call up into the root state.
In both cases, the fact that a single sub-state might depend on just one or many atomic states makes state verification very convoluted and I end up with non-acceptable, bloated code. I feel like I need a different kind of approach, but I'm stuck on the current design. If anyone has experience with this kind of problem and can offer some inspiration, I would really appreciate.
One quick thought:
1) Observer pattern between composite and atomic states ("a", "b", "c" as observees and "A" as observer, so on..)
2) Have class-A implemented using Pimpl idiom to separate the interface & implementation details, thus have more control and exhibit more flexibily in changing the implementation details.
3) Let class-A have some kind of Factory abstraction to create & manage specialized implementation-objects for each unique state of "A".
4) Thus, whenever changes on a, b, c are observed by "A", Factory helps to retrieve the corresponding implementation-state of "A" and does a state change.
Apply same approach between "A" and "X".
More detailed layout:
1) Define the required interfaces (generic or abstract classes) IX, IA, Ia, Ib, Ic.
2) In interface IA, define public IaChanged(Ia*), IbChanged(Ib*) & IcChanged(Ic*) methods to receive Ia, Ib & Ic state change notifications (Callback methods of Observer pattern).
3) Inside the atomic interfaces Ia, Ib & Ic. Define public Register(IA&) & private Notify() metods.
In Interface Ia,
Where Notify() { foreach(observer in m_Observers)
observer->IaChanged(this);
}
In Interface Ib,
Where Notify() { foreach(observer in m_Observers)
observer->IbChanged(this);
}
so on...
4) Have clases X, A, a, b, c derived from respective interfaces.
X->IX, A->IA, a->Ia, b->Ib & c->Ic, where -> represents "derives".
5) Have class A define A_implState (Pimpl Idiom), where A_implState may derive from a new interface IA_implState to keep things generic.
Have classes A_implState0, A_implState1, A_implState2, A_implStateX as specialized versions of IA_implState.
where,
class IA_implState
{
public:
virtual void processStateChange()=0;
};
class A_implState0 : public IA_implState
{
public:
void processStateChange()
{
// do your stuff specific to State "0" of "A".
}
};
class A_implStateX : public IA_implState
{
public:
void processStateChange()
{
// do your stuff specific to State "X" of "A".
}
};
so on...
6) Have one specialization of IA_Impl for each distinct states of A, based on:
a b c - A
0 0 0 - 0
1 0 0 - 1
2 0 0 - x
2 1 0 - 2
7) In class A, whenever IaChanged(IaPtr) or IbChanged(IbPtr) or IcChanged(IcPtr) gets triggered by respective observee, process the change notifications as:
// a changed
void A::IaChanged(IaPtr a)
{
//Buffer Ia inside a member
m_pIa = a;
//Retrieve A-implementer based on the current state.
m_pimplA = m_implAContainer[GetCurrentState()]; // or use FactoryMethod or AbstractFactory pattern if required.
m_pimplA->processStateChange();
}
// b changed
void A::IbChanged(IbPtr b)
{
//Buffer Ib inside a member
m_pIb = b;
m_pimplA = m_implAContainer[GetCurrentState()]; // use FactoryMethod or AbstractFactory pattern if required.
m_pimplA->processStateChange();
}
/* a rough sketch, may look like */
use shared_pointers for managing lifetime, define some typedefs for ease of use.
typedef std::shared_ptr<Ia> IaPtr;
typedef std::shared_ptr<Ib> IbPtr;
typedef std::shared_ptr<IA_impl> IAImplPtr;
typedef std::map<int /* or other datatype as required */ , IA_implPtr> ImplAPtrContainer;
// class-A may look like
class A : public IA
{
public:
void IaChanged(const IaPtr ptr_a);
void IbChanged(const IbPtr ptr_b);
void Init();
void DeInit() { m_implAContainer.clear(); }
private:
int GetCurrentState();
private:
ImplAPtrContainer m_implAContainer;
IAImplPtr m_pimplA;
IaPtr m_aPtr;
IbPtr m_bPtr;
IcPtr m_cPtr;
};
// Initialize Container with all possible implementation states for class-A
void A::Init()
{
m_implAContainer.insert(/*state*/ 0, IAImplPtr(new A_implState0));
m_implAContainer.insert(/*state*/ 1, IAImplPtr(new A_implState1));
m_implAContainer.insert(/*state*/ X, IAImplPtr(new A_implStateX));
}
// Determine the A's current state based on a, b & c' current state
int A::GetCurrentState()
{
// Have this method return A's state based on a b c, prefer enums over magic numbers
if(m_aPtr->GetState() == 0 && m_bPtr->GetState() == 0 && m_cPtr->GetState() == 0)
return 0;
}

Uppercase letter using C++ preprocessor (x -> getX/setX)

I would like to define some properties like:
#define property(T, x) T x; T get ## x (); void set ## x (T value);
class foo {
public:
property(int, count);
property(float, size);
}
but I would like methods to be called getCount/setCount and not getcount/setcount.
As the comment says, you cannot do that. Preprocessor doesn't do those kind of things.
So either you follow what #Shahbaz said in the very first comment, or do something like this which gives you get and set of get_count and set_count form.
#define property(T, x) private : T m_## x; \
public : T get_## x () { return m_## x;} \
void set_## x (T value) { m_## x = value; }
class foo {
public:
property(int, count);
property(float, size);
};
int main() {
foo f;
f.set_count(10);
std::cout << f.get_count() << std::endl;
return 0;
}
Quick demo at ideone
Note that the variable is declared in the private section and its name is m_count, and the functions are defined (not only declared) in the public section.
Or, you could pass Count instead of count in the macro as:
property(int, Count);
If you do so, then you could create the variable as m_Count and functions as getCount and setCount. That is closest to what you want.
No way (that I know of) to do this using the C pre-processor. I'd suggest as a compromise, you go for an underscore and use get_count() which is easily read. Other alternatives:
If you really want to stick with a pre-processor you could investigate using m4 as a first step. It's definitely possible with m4 as I've done something very similar. That said, this seems a bit complicated for what you want to achieve.
Add an extra parameter so you get #define property(T, x, name) which allows you to specify the name seperately. It's more flexible but again probably not what you want.
If it's really just the legwork of creating the accessors / mutators, there are plenty of IDEs and code generators that will do it for you or you could write some shell / Python / Perl to knock this out as a one off very easily.
Two final observations: Although it might seem more efficient to write it this way, remember that anyone maintaining your code may well do a search for setCount() and not find it which will waste time until they puzzle out what you've done. I.e. from a code maintennce perspective, keep it simple. Secondly, it's good practice to denote macros in upper case, since that way they are easily identified as such. Again this really helps when you're maintaining code.