Simpler Haskell development with Nix

August 17, 2016

If you use Nix, here's a super simple way to do rapid development in Haskell. This approach simplifies those in Haskell development with Nix, which rely on tedious one-off Nix configuration files and Cabal.

Create a function nix-haskell in your shell configuration file:

~/.bashrc:

function nix-haskell() {
  nix-shell -p "haskellPackages.ghcWithPackages (pkgs: with pkgs; [$@])"
}

This will start a nix-shell instance with GHC, and an environment configured with the list of packages that you supply as arguments:

$ nix-haskell random
[nix-shell]$

Now you can write library-dependent Haskell code without needing Cabal, Stack, etc.

Slug.hs:

{-# LANGUAGE OverloadedStrings #-}

import Control.Monad (replicateM)
import System.Random (randomRIO)

alphabet :: String
alphabet = ['a'..'z'] ++ ['0'..'9']

randomElem :: String -> IO Char
randomElem l = randomRIO (0, ((length l) - 1)) >>= \d -> return (l !! d)

main :: IO ()
main = do
  slug <- replicateM 12 (randomElem alphabet)
  putStrLn $ "Random slug: " ++ slug
[nix-shell]$ runhaskell Slug.hs
Random slug: 2tm997e9ko1p

This post is literate Haskell. Try running it with codedown:

$ nix-haskell random
$ curl https://earldouglas.com/nix-haskell-2.md |
  codedown haskell |
  runhaskell
Random slug: m6n9t3xm9pvy