Making Haskell useful

During the last week I’ve been trying to brush up on my Haskell. Me trying to learn Haskell has been a reoccurring event for the past years. This video was a real turn off last time.

But this time I finally think I see how Haskell can be useful. The new discovery is the Haskell FFI system. The Foreign Function Interface. It’s a simple system that allows you to integrate your Haskell program right into other native binaries. This means, the things that Haskell is useless with, low level operations, performance code, platform specifics, unsafe code, general IO etc; can be implemented in another language. And you are left with a more pure implementation of the code model in Haskell.

I’ve made a small code example showing of basic FFI:

{-# LANGUAGE ForeignFunctionInterface #-}

import Foreign
import Foreign.C.Types

foreign import ccall hello :: CInt -> IO ()

main :: IO ()
main = do
    putStrLn "Hello World"
    mapM_ hello [1..4]

And the non Haskell part in C:

#include <stdio.h>

void hello(int x) {
    printf("Let's print this number: %d\n", x);
}

This code can be compiled using different compilers:

ghc -c ffi.hs -o ffi.o
gcc -c ffi_c.c -o ffi_c.o
ghc ffi.o ffi_c.o -o ffi

You can get a Haskell environment that limits IO operations to your non Haskell part.

There you can put all your dirty impure code, and write it in a language that is actually suitable for dirty operations.

Leave a Reply

Your email address will not be published. Required fields are marked *