Calling C++ libraries (especially template based like CGAL) from Haskell - c++

I have been using Haskell for a few months and would really like to use it in one of my projects involving computational geometry.
Haskell however, sorely lacks in good geometry libraries. Geometric algorithms are notoriously hard to implement robustly, hence I would like to use an off-the-shelf package like CGAL. It makes heavy use of C++ templates. I won't be needing an interface to all of CGAL, just a small subset of functions which I use most of the time.
Haskell has a good C foreign function interface, but not for C++. So how can I call C++ through Haskell?
All I found was this https://wiki.haskell.org/CPlusPlus_from_Haskell which seems a complicated way of going about the process. I am sure people have a simpler way of calling C++ from Haskell.

Related

Is it possible to use tuples in c++ with Gurobi?

I am trying to solve a SOCP using Gurobi, in a C++ project. From what I know, Gurobi does not support complex numbers, but I have seen that with python it is possible to use tuples as variables, which it would be a great alternative.
However, I've tried to search online and I couldn't find anything about using tuples with Gurobi in C++. Is there a way to do it?
After few days of more research (and after implementing the code I needed in Python), I'll post an answer to my own question. In the Gurobi documentation, the developers admit themselves that the Python API offers more in comparison with the API of other programming languages:
If you don't have a strong preference, we recommend that you use our Python® interface, which provides a number of benefits. First, Python is a very nice programming language that can be used for anything from experimentation to prototyping to deployment. Beyond this, though, our Python interface includes a set of higher-level modeling constructs that make it much easier to build optimization models.
So, I "solved" the problem by modelling and solving the SOCP with a Python script, which is called by my C++ code and to which I'm passing back the result of the optimization process.

Mixing Haskell and C++

If you had the possibility of having an application that would use both Haskell and C++.
What layers would you let Haskell-managed and what layers would you let C++-managed ?
Has any one ever done such an association, (surely) ?
(the Haskell site tells it's really easy because Haskell has a mode where it can be compiled in C by gcc)
At first I think I would keep all I/O operations in the C++ layers. As well as GUI management.
It is pretty vague a question, but as I am planning to learn Haskell, I was thinking about delegating some work to Haskell-code (I learn in actually coding), and I want to choose some part where I will see Haskell benefits.
The benefit of Haskell is the powerful abstractions it allows you to use. You're not thinking in terms of ones and zeros and addresses and registers but computations and type properties and continuations.
The benefit of C++ is how tightly you can optimize it when necessary. You aren't thinking about high-minded monads, arrows, partial application, and composing pure functions: with C++, you can get right down to the bare metal!
There's tension between these two statements. In his paper “Structured Programming with go to statements,” Donald Knuth wrote
I have felt for a long time that a talent for programming consists largely of the ability to switch readily from microscopic to macroscopic views of things, i.e., to change levels of abstraction fluently.
Knowing how to use Haskell and C++ but also how and when to combine them well will knock down all sorts of problems.
The last big project I wrote that used FFI involved using an in-house radar modeling library written in C. Reimplementing it would have been silly, and expressing the high-level logic of the rest of the application would have been a pain. I kept the “brains” of it in Haskell and called the C library when I needed it.
You're wanting to do this as an exercise, so I'd recommend the same approach: write the smarts in Haskell. Shackling Haskell as a slave to C++ will probably end up frustrating you or making you feel as though you wasted your time. Use each language where its strengths lie.
Here is how I see things:
Functional languages excel at transforming things. Whenever you write programs which take an input and map/filter/reduce it, use functional constructs. Wonderful real world examples where Haskell should excel are given by web applications (you basically transform things stored in a database to web pages).
Procedural languages (OOP languages are procedural) excel at side effects and communication between objects. They are cumbersome to use to transform data, but whenever you want to do system programming or (bidirectional) interaction with humans (user interfaces of any kind, including client-side web programming), they do the job cleanly.
However, some may argue that user interfaces should have a functional description, I answer that well established frameworks are easy enough to use with OOP languages that one should use them this way. After all, it is natural to think of UI components in terms of objects and communication between objects.
IO is only a tool: whenever you transform input to output, Haskell (or whatever FP language) should do the IO. Whenever you speak to a human, C++ (or whatever OOP language) should do the IO.
Don't care about speed. When you use Haskell for the right job, it's efficient. When you use C++ or Python for the right job, it's efficient.
Therefore, let's say I'm fluent in Haskell, C, C++ and Python, here's how I write applications:
If my application's main role is to transform data, I write it in Haskell, with possibly some low-level parts written in C (which may, in turn, call some high-tech low level parts written in C++, but I'd stick with C as an interface for portability reasons).
If my application's main role is to interact with a user, I write it in Python (PyQt for instance), and let Python call performance-critical routines written in C++ (boost::python is pretty good as a binding generator). I may also have to call subroutines which transform or fetch data, which will be written in Haskell.
If I have to write a part of an application in Haskell, I segregate it into a C-callable API.
Sometimes, a Haskell application which reads things on stdin and write back on stdout is useful as a submodule (that you call with fork/exec, or whatever on your platform). Sometimes, a shell script is the right wrapper for such applications.
This answer is more a story than a comprehensive answer, but I used a mix of Haskell, Python and C++ for my dissertation in computational linguistics, as well as several C and Java tools that I didn't write. I found it simplest to run everything as a separate process, using Python as glue code to start the Haskell, C++ and Java programs.
The C++ was a fairly simple, tight loop that counted feature occurrences. Basically all it did was math and simple I/O. I actually controlled options by having the Python glue code write out a header full of #defines and recompiling. Kind of hacky, but it worked.
The Haskell was all the intermediate processing: taking the complex output from the various C and Java parsers that I used, filtering extraneous data, and transforming it the simple format the C++ code expected. Then I took the C++ output and transformed it into LaTeX markup (among other formats).
This is an area that you would expect Python to be strong, but I found that Haskell makes manipulation of complex structures easier; Python is probably better for simple line-to-line transformations, but I was slicing and dicing parse trees and I found that I forgot the input and output types when I wrote code in Python.
Since I was using Haskell a lot like a more-structured scripting language, I ended up writing a few file I/O utilities, but beyond that, the built in libraries for tree and list manipulation sufficed.
In summary, if you have a problem like mine, I would suggest C++ for the memory-constrained, speed-critical part, Haskell for the high-level transformations, and Python to run it all.
I have never mixed both languages but your approach feels a little upside down to me.
Haskell is more apt at high-level operations while C++ can be optimized and can be most beneficial for tight loops and other performance critical code.
One of the largest benefits of Haskell is the encapsulation of IO into monads. As long as this IO isn't time critical I don't see any reason to do it in C++.
For the GUI part you are probably right. There is a plethora of Haskell GUI libraries but C++ has powerful tools such as QtCreator which simplify the tedious tasks a lot.

A generic C++ library that provides QtConcurrent functionality?

QtConcurrent is awesome.
I'll let the Qt docs speak for themselves:
QtConcurrent includes functional programming style APIs for parallel list processing, including a MapReduce and FilterReduce implementation for shared-memory (non-distributed) systems, and classes for managing asynchronous computations in GUI applications.
For instance, you give QtConcurrent::map() an iterable sequence and a function that accepts items of the type stored in the sequence, and that function is applied to all the items in the collection. This is done in a multi-threaded manner, with a thread pool equal to the number of logical CPU's on the system.
There are plenty of other function in QtConcurrent, like filter(), filteredReduced() etc. The standard CompSci map/reduce functions and the like.
I'm totally in love with this, but I'm starting work on an OSS project that will not be using the Qt framework. It's a library, and I don't want to force others to depend on such a large framework like Qt. I'm trying to keep external dependencies to a minimum (it's the decent thing to do).
I'm looking for a generic C++ framework that provides the same/similar high-level primitives that QtConcurrent does, and that works with STL collections. AFAIK boost has nothing like this (I may be wrong though). boost::thread is very low-level compared to what I'm looking for (but if the requested lib used boost::thread for the low-level work, that would be great).
I know C# has something very similar with their Parallel Extensions so I know this isn't a Qt-only idea.
What do you suggest I use?
I've heard good things about Intel's Threaded Building Blocks, though I haven't used it
As of Oct 2009, it doesn't seem to have map-reduce specifically. But people have expressed interest and suggested they were going to come up with something:
http://software.intel.com/en-us/forums/showthread.php?t=65053
"map reduce looks like a simple combination of a filter, a sort, and a reduction but it might need some magic to get it to be efficient"
Can you use Boost? I don't think it provides quite as high-abstraction a layer as Qt, but it should be possible to make one as a reasonably thin facade on top of Boost's primitives (indeed, maybe some of the existing add-ons already provide what you require -- I have to admit I'm not familiar with them in detail, which is why I say "maybe";-).
If you find out that existing add-ons are unsuitable, your facade would be an excellent add-on to contribute to the Boost Vault (or other open-source repo) yourself, "giving back" a useful reusable open-source contribution... I hope this motivates you to do this work if needed!-)

Functional programming in C++11, F# style

I've been looking at the new features in C++11 and it really looks like it will be possible to program in a very functional programming style using it. I've gotten use to using the types List, Seq, Array in F# and I see no reason why their members couldn't be ported into some sort of C++11 template. What problems or advantages do you see in using C++11 vs something like F# for a mixed functional programming style? Maybe the Boost guys will make a new functional once C++11 comes out.
The biggest problem with trying to program in a functional style in C++ is that it does not support tail recursion. In a functional language you don't have to worry about stack explosion when you tail recurse correctly, but in C++ you always have to worry about that. Therefore, many "functional" type algorithms will be clumsy or heavy.
Here are some of the problems I encountered trying to write functional code in C#, mixed with some goodies from my time when I was still using C++:
Lack of pattern matching. Once you get used to it, not having it can drive me crazy.
Lack of syntactic sugar for tuples.
Lack of syntax for copying records and setting fields in one go.
Lack of syntax for lists and arrays. That goes for constructors and pattern-matching.
Not having a GC, and unsafe memory accesses. Not being constrained by a GC is an advantage, but remembering the reports I got from my first runs of Valgrind on C++ code I thought was bug free scared me for ever.
Understanding template code isn't exactly accessible to all mortals. I don't have problem understanding mine, but whenever I looked into implementations of the STL, boost or cgal I found myself wondering what language they were using. My C++ and their C++ don't live in the same world.
The total lack of fun in dealing with a library that uses another version of boost (or any library that uses templates).
Verbosity of separate header/implementation files.
Type inference in C++ does not go as far as e.g. F#. I know it's been improved in C++11, but as I understand it's similar to var in C#, which isn't enough once you tasted F#-style inference.
Lack of computation expressions, including sequence expressions, comprehensions, async...
It would not surprise me if several of these points were actually possible in C++ using some template and preprocessor magic, but you can't really use these in a production environment unless you have very adventurous and tolerant co-workers.
I was a die-hard C++ enthusiast before. Then I started using generic programming with templates and higher-order functions using function objects. It just was too tiresome to write. After I tried a functional language I never looked back.
You might find this interesting:
http://smellegantcode.wordpress.com/2009/01/26/linq-to-c0x/
What problems of advantages do you see in using c++0x vs something like f# for a mixed functional programming style?
The upward funarg problem, which was debated in the context of Lisp 40 years ago!
I imagine that it would be… interesting… to implement certain optimizations common to functional languages in C++0x (like common subexpression elimination).

How do you glue Lua to C++ code?

Do you use Luabind, toLua++, or some other library (if so, which one) or none at all?
For each approach, what are the pro's and con's?
I can't really agree with the 'roll your own' vote, binding basic types and static C functions to Lua is trivial, yes, but the picture changes the moment you start dealing with tables and metatables; things go trickier very quickly.
LuaBind seems to do the job, but I have a philosophical issue with it. For me it seems like if your types are already complicated the fact that Luabind is heavily templated is not going to make your code any easier to follow, as a friend of mine said "you'll need Herb Shutter to figure out the compilation messages". Plus it depends on Boost, plus compilation times get a serious hit, etc.
After trying a few bindings, Tolua++ seems the best. Tolua doesn't seem to be very much in development, where as Tolua++ seems to work fine (plus half the 'Tolua' tutorials out there are, in fact, 'Tolua++' tutorials, trust me on that:) Tolua does generate the right stuff, the source can be modified and it seems to deal with complicated cases (like templates, unions, nameless structs, etc, etc)
The biggest issue with Tolua++ seems to be the lack of proper tutorials, pre-set Visual Studio projects, or the fact that the command line is a bit tricky to follow (you path/files can't have white spaces -in Windows at least- and so on) Still, for me it is the winner.
To answer my own question in part:
Luabind: once you know how to bind methods and classes via this awkward template syntax, it's pretty straightforward and easy to add new bindings. However, luabind has a significant performance impact and shouldn't be used for realtime applications. About 5-20 times more overhead than calling C functions that manipulate the stack directly.
I don't use any library. I have used SWIG to expose a C library some time ago, but there was too much overhead, and I stop using it.
The pros are better performance and more control, but its takes more time to write.
Use raw Lua API for your bindings -- and keep them simple. Take inspiration in the API itself (AUX library) and libraries by Lua authors.
With some practice raw API is the best option -- maximum flexibility and minimum of unneeded overhead. You've got what you want and no more, the way you need it to be.
If you must bind large third-party libraries use automated generators like tolua, tolua++ (or even roll your own for the specific case). It would free you from manual work.
I would not recommend using Luabind. At the moment it's development stalled (however starting to come back to life), and if you would meet some corner case, you may be on your own. Also Luabind heavily uses template metaprogramming. This may (and may not) be unacceptable, depending on the point of view.