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

• Programs are written in natural language
• Interspersed with snippets of code
• Snippets extracted to compilable source code

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

• Denoted by lines beginning with ""
• From text files named with an `.lhs` extension

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.``````

Interpret and run:

``````\$ runghc fact.lhs
120``````

Compile and run:

``````\$ ghc fact.lhs
\$ ./fact
120``````

# Codedown

Codedown can extract code blocks:

• Of any given language (marked by ```lang)
• From any Markdown file

# 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 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 https://earldouglas.com/talks/codedown/slides.md | codedown scala | xargs -0 scala -nc -e``

Output:

``120``

# Demo 