Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write platform-independent code in Haskell (ghc)

Tags:

There are a few platform-specific libraries in Hackage that I'd like to use (e.g. inotify, kqueue). However, documentation on how to switch between platforms using conditional compilation seems a little bit sparse. I'm having some trouble finding the relevant docs...

  1. Which preprocessor definitions can I use to switch between platforms?

  2. How can I set up my cabal file to include/exclude inotify/kqueue on linux/osx respectively?

I hope that having it documented here might be useful for others too, so it may be worthwhile to mention other common platforms. It's silly to look for this stuff all over the place.

like image 211
Rehno Lindeque Avatar asked Dec 10 '12 10:12

Rehno Lindeque


People also ask

What is the difference between GHC and ghci?

GHCi is the interactive interface to GHC. From the command line, enter "ghci" (or "ghci -W") followed by an optional filename to load. Note: We recommend using "ghci -W", which tells GHC to output useful warning messages in more situations. These warnings help to avoid common programming errors.

How do I run a terminal code in Haskell?

If you have installed the Haskell Platform, open a terminal and type ghci (the name of the executable of the GHC interpreter) at the command prompt. Alternatively, if you are on Windows, you may choose WinGHCi in the Start menu. And you are presented with a prompt. The Haskell system now attentively awaits your input.

How do I run a compiled Haskell file?

Open a command window and navigate to the directory where you want to keep your Haskell source files. Run Haskell by typing ghci or ghci MyFile. hs. (The "i" in "GHCi" stands for "interactive", as opposed to compiling and producing an executable file.)

What does Haskell compile to?

Unlike Python, Ruby, JavaScript, Lua, and other interpreted languages, Haskell is compiled ahead-of-time, directly to native machine code.


1 Answers

  1. Take a look at the os_HOST_OS flags in combination with the C preprocessor option -cpp (or using {-# LANGUAGE CPP #-}) as stated in the GHC documentation

  2. Add extensions: CPP to your package description as shown in the Cabal documentation and define a custom flag like this:

    if os(linux)
         cpp-options: -DINOTIFY
    if os(darwin)
         cpp-options: -DKQUEUE
    

You can then use #ifdef in your source.

like image 69
Secoe Avatar answered Nov 01 '22 17:11

Secoe