sumRoots :: [Double] -> Double sumRoots xs = sum (map sqrt xs)

Every argument must be a Ptr to a C compatible type, typically Int , Double or CString . (To be pedantic, we should probably use CInt or CDouble , but using GHC on Windows these types are equivalent - keeping things simpler.)

to a C compatible type, typically , or . (To be pedantic, we should probably use or , but using GHC on Windows these types are equivalent - keeping things simpler.) The result must be IO ()

sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO () sumRootsR n xs result = ...

xs

n , the length of the list xs

, the length of the list xs , the elements of the list

, the elements of the list result , a space to put the result

sumRootsR

Foreign

sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO () sumRootsR n xs result = do n <- peek n xs <- peekArray n xs poke result $ sumRoots xs

n

0..n-1

xs

sumRoots

sumRoots

sumRootsR

foreign export ccall sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO ()

-- SumRoots.hs {-# LANGUAGE ForeignFunctionInterface #-} module SumRoots where import Foreign foreign export ccall sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO () sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO () sumRootsR n xs result = do n Double sumRoots xs = sum (map sqrt xs)

// StartEnd.c #include <Rts.h> void HsStart() { int argc = 1; char* argv[] = {"ghcDll", NULL}; // argv must end with NULL // Initialize Haskell runtime char** args = argv; hs_init(&argc, &args); } void HsEnd() { hs_exit(); }

ghc -c SumRoots.hs ghc -c StartEnd.c ghc -shared -o SumRoots.dll SumRoots.o StartEnd.o

SumRoots.dll

dyn.load("C:/SumRoots.dll") # use the full path to the SumRoots library .C("HsStart")

input = c(9,3.5,5.58,64.1,12.54) .C("sumRootsR", n=as.integer(length(input)), xs=as.double(input), result=as.double(0))$result

sumRoots Now we can write: sumRoots(c(12,444.34)) And get back the answer 24.54348. With a small amount of glue code, it's easy to call Haskell libraries from R programs. Update: See the comments below from Alex Davis for how to do such things on newer versions of Mac OS.