Literate programming with Codedown

James Earl Douglas

May 29, 2016

Literate programming

Introduced by Donald Knuth in his book Literate Programming.

"The main idea is to regard a program as a communication to human beings rather than as a set of instructions to a computer." -- Donald Knuth

Literate Haskell

Haskell (ghc, runghc, etc.) can extract code blocks:

Literate Haskell

fact.lhs:

Here's a recursive factorial implementation:

> fact :: Integer -> Integer
> fact 0 = 1
> fact n = n * fact (n-1)

We can try it from our `main` function:

> main :: IO ()
> main = putStrLn fact5S where
>   fact5  = fact 5
>   fact5S = show fact5

This prints `120` to standard out.

Literate Haskell

Interpret and run:

$ runghc fact.lhs
120

Compile and run:

$ ghc fact.lhs
$ ./fact
120

Codedown

Codedown can extract code blocks:

Codedown

Here's a Scala implementation of recursive factorial:

def fact(n: Int): Int =
  n match {
    case 0 => 1
    case _ => n * fact (n-1)
  }

And here's a sample usage of it:

val fact5: Int = fact(5)
println(fact5)

Codedown

$ curl -s https://earldouglas.com/talks/codedown/slides.md | codedown scala

Output:

def fact(n: Int): Int =
  n match {
    case 0 => 1
    case _ => n * fact (n-1)
  }

val fact5: Int = fact(5)
println(fact5)

Codedown

$ curl -s https://earldouglas.com/talks/codedown/slides.md | codedown scala | xargs -0 scala -e

Output:

120

Demo

References