tags:

views:

388

answers:

5

I'm looking an efficient way of executing Haskell functions from within a Java program. I've considered the use of exec() to interact with GHC, but it seems like there should be a better method.

+2  A: 

See Interfacing with other languages: Java on the Haskell wiki.

Greg Bacon
Those focus on invoking Java code from Haskell. I was looking for something that works the other way.
ViralShah
Actually, isn't the Haskell/Java VM bridge what you are looking for? It's JNI.
Nathan Sanders
+4  A: 

I assume you know how to call C from Java? If so, then you can follow the FFI guide to call Haskell from C, and C from Java, creating a bridge. This is a native call, and may require some fiddling with linkers.

Details on calling Haskell from C are here: http://www.haskell.org/haskellwiki/Calling_Haskell_from_C

Alternatively, you might consider an RPC server.

Don Stewart
A: 

I can't always tell on the wiki what version it's referring to, so I go to the ghc docs. See section: 9.2.1.2. Making a Haskell library that can be called from foreign code

Do you expect the haskell code to be long running or short running? How often do you expect to call into the Haskell code? How acceptable/amortizable are the startup costs of initializing the ghc runtime? Your answers there will determine the best way to call.

ja
The Haskell functions will be generated by the user and should have a relatively short running time (less than 10 seconds). Ideally the GHC instance should be left running and execute functions as they as are passed in, opposed to starting-up and closing for every function call.
ViralShah
A: 

Easiest way I can think of: start up hint in a separate process. As a quick demonstration, something dumb like

import Control.Monad
import Language.Haskell.Interpreter
main = getContents >>= mapM_ (eval >=> print) . lines

can be fed expressions on stdin and will give stringy results on stdout. Of course, it'll take a little more work to make sure this is safe.

(Err, assuming Java has some sort of popen2-ish functionality. Otherwise maybe you can do the same over sockets.)

ephemient
+4  A: 

I usually avoid JNI-type approaches to linking across runtimes/languages. They just have too many gotchas and little upside. I find it easier to work across process boundaries. While I've never tried it with Haskell and Java, they both have libraries that support XML RPC, and it sounds like a natural fit for what you're doing. So: set up a Haskell program as a "service" and just call its functions when you need them.

Isaac Cambron
And there are reasonable xml-rpx libraries, http://hackage.haskell.org/package/haxr
Don Stewart