Haskell + lhs2TeX + LaTeX beamer

May 16, 2008

For a presentation I’m currently building I want to walk the public through a bit of Haskell code. Because I want to make sure my code is runnable too, I decided to write it as Literal Haskell and then use lhs2TeX to convert it to very pretty LaTeX which I use to make a presention PDF with LaTeX Beamer.

This is pretty easy for the common use case (a (research) paper) about Haskell), but I had some more requirements.

  • The code is split over several files
  • I want to mix code fragments of those files
  • I want effects, like uncovering code line by line

It took me a couple of hours to figure out a sensible approach, which I describe here. I’m sure there are more ways to do it, and I’d love to hear them!

Since our lhs2TeX activities will be spread over multiple files, we’ll want to make a simple formatting file to share. Let’s call it ‘talk.fmt’

%include polycode.fmt

% put formatting rules here

Then we set up our main LaTeX file. Because we might want to use some code examples in there that are not in the files, let’s make it an lhs-file: ‘talk.lhs’. In it’s preamble we define a couple of new LaTeX commands that are going to help us with making slides but referencing them in an arbitrary order.


%include talk.fmt








First, we have ‘\ignore’ to hide stuff from LaTeX that is only useful in the code and we don’t want to have in our presentation.

The ‘\defslide’ command takes two arguments, a name which is used as a label to reference to and the contents for the slide. The ‘<hidden>’ makes sure that these slides will not be rendered. In this case ‘hidden’ is not a special argument, just a non-existing ‘mode’.

To use a defined slide, we use ‘\slide’, which uses ‘\againslide’ to draw the slide, with all possible subframes (‘<1->’).

In the document body we include all the files which contain slides. Note that this should be .tex file, generated from our .lhs file. For example ‘Code.lhs’ could look like this.

%include talk.fmt

module Code where

>                     example :: IO ()
> {-"\uncover<2->{"-} example = putStrLn "Hello!" {-"}"-}

\frametitle{Just a normal frame}
main :: IO ()
main = undefined

I don’t uncourage anybody to mix styles like this, it’s just an a example, okay? ūüėČ What you also see here is the way to uncover a piece of code line by line. If you want to learn more about LaTeX Beamer I suggest you consult the fine manual.

For easy use, we can make a Makefile to tie everything up. We also use latexmk, a simple tool that automagically processes the LaTeX file as many times as necessary, which saves a ton of time.

default: talk.pdf

talk.pdf : Code.tex

%.pdf : %.tex
    latexmk -pdf $<

%.tex : %.lhs talk.fmt
    lhs2TeX $< > $@

    latexmk -CA talk

If you want to try it for yourself just copy the above code to the mentioned filenames and run ‘make’ to get the pdf. (Provided you have all the necessary requirements.)

(I think I massaged all the code so that it gets through WordPress’ botching, but you’ll still need to replace the indenting spaces with tabs in the Makefile yourself.)

While in this example only one file with code is used, it easy to see that this way as many files as necessary can be used. As shown, the slides can be in arbitrary order and we can use nice LaTeX Beamer effects like uncovering. Hooray!


Just for fun: map as ‘higher-order function’ in bash

March 8, 2008

Defined recursively, of course:

map () { 
  if [ $# -le 1 ]; then 
    local f=$1 
    local x=$2 
    shift 2 
    local xs=$@ 

    $f $x 

    map "$f" $xs 

I’m not going to explain everything, but note the ‘local’ commands to keep everything in function scope (to prevent strange bugs) and the quotes around $f in the recursive call to prevent a ‘function call’ of multiple words from being split.

Now you can do some completely nonsensical things, for which you really don’t need map, such as:

$ map touch aap noot mies

But also slightly more useful things such as

$ map "echo foo" aap noot mies 
foo aap 
foo noot 
foo mies 

$ map "echo file:" `ls` 
file: aap 
file: noot 
file: mies

To open up some more possibilities, I also defined a ‘rota’ function, with rotates the arguments of a command such that the last comes first.

rota () { 
  local f=$1 
  local args=($@) 
  local idx=$(($#-1)) 
  local last=${args[$idx]} 

  $f $last ${args[@]} 

I’m using a array (yes, bash has arrays) to easily get the last element, as you can see ūüėČ

So, how about…

$ map "rota mv /tmp" aap noot mies

(Move the aap, noot and mies file to /tmp)

There are probably better (and more useful) examples of it’s usage, but you hopefully get the gist of it.

This code is just for fun (I don’t expect I’m ever going to use it, even), so it’s nowhere near being robust. There are a lot of (possible) bugs concerning spaces and undetected grouping of words (with double quotes). Use at your own risk ūüėČ


Beautiful timetables

November 11, 2007

Because I wanted a clear and compact way to display the timetable of the tram nearby, I created a small project. My goal was to have something more ‘visual’ than a list with numbers. I am interested in new ways to display information and what’s nice about it and why.

Preview of output

I think the result is something that has a bit of a learning curve and is therefore less suitable for ‘one-time’ usage. On the other hand, because it’s more of a picture and not a bunch of numbers I think it’s much easier to learn the timetable by heart for regular users.

For specification I wanted a small and simple language and preferably not start with writing a parser, so I decided to hitch a ride with Haskell first.

I’d love to hear your opinion, both a first reaction and after experimenting with it.

¬Ľ Download it

(view readme or view haskell module)


A little puzzle

October 14, 2007

A couple of years ago, I learned about a fun little puzzle. The question is: what’s the next element in the following sequence:

1 1
2 1
1 2 1 1
1 1 1 2 2 1

Once I solved the puzzle, I wanted to see if I could come up with a short function that generates this sequence. This is my haskell version:

next [] = []
next (x:xs) = [length start + 1,x] ++ next end
where (start, end) = span (== x) xs

You can call it like this:

main = mapM (putStrLn . unwords . map show) (iterate next [1])

Update: Martijn told me about some background behind this sequence. It’s called the Look and Say Sequence, and it’s a quite interesting sequence indeed.


Improving Vim’s Mac integration

July 17, 2007

Update: our first patch is now available!

Vim is a great editor and OS X a lovely operating system, but unfortunately, they do not go really well together.  No wonder requests for better OS X integration are at the top of the requested features list.

But so far the Mac Vim community doesn’t seem to have the manpower to get cranking on these issues. Luckily there’s Jjgod Jiang working on a Summer Of Code project to build a Cocoa GUI for vim.

As avid Vim users we’d like to contribute something as well. So we took the week off and started hacking (with just a grain of C knowlegde and no prior Mac API experience) Vim to implement the ODB Editor Suite which will make it possible to use Vim from a whole bunch of FTP applications. We’re making progress and hope to ‘release’ a first version patch soon.

If time allows we’ll also try to develop a simple ‘Edit in Vim’ button that can be used from text widgets in any application.


Mac OS X: Duplicate your Terminal-window in the same directory

June 11, 2007

I was looking for a way to duplicate the current Terminal-window in the same directory. I wrote a
small script that does just this, save it as ~/bin/dup

echo "cd `pwd`" > ~/.bash_last_dir
echo "rm ~/.bash_last_dir" >> ~/.bash_last_dir
echo "touch ~/.bash_last_dir" >> ~/.bash_last_dir
open -a Terminal .

If you include the following line at the end of your ~/.bash_login, you’re all set:

source ~/.bash_last_dir

Make sure the ~/bin directory is in your path, and type “dup” in your Terminal to duplicate it.


V: find and edit files quickly via your commandline

April 23, 2007

I’m working on a project with a lot of files. Most of the time, I know exactly which file I want to edit. However, because everything is nicely organized in directories and packages, it’s very tedious to keep typing a long file-path.

I created a small tool which recursively searches for the (partial) filename you provide in the current directory. If it finds only one match, it will launch vim for that file. If it finds more matches, it will show you a list of files to choose from. It will remember your choice, and assign a weight to that file, so that it will bubble to the top of the list next time.

Currently the weight is assigned to the relative filepath. This means that you can easily switch to another branch of your project if it has the same structure. It also means that you always have to run the program from the root of your project.

As a small bonus I added a feature where you can specify the command to run. By default it is vim, but if you provide a different command as the second argument, it will launch that command. For example, you can run it as “v myfile less”, which will open the selected file in less instead of vim.

I hope you enjoy it, let me know if you do. Here’s the link: v.rb. Save the file somewhere in your path.


Ruby and elegance: Transpose

March 10, 2007

I recently found that the Array class of Ruby has a zip method, which works much like Haskell’s zip function, except that it allows multiple arguments.

For example:

$ irb --simple-prompt
>> [1,2,3].zip [4,5,6], [7,8,9]
=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

The night after I did this little experiment I suddenly realized: this is a transpose function! I quickly got out of bed to document my little discovery:

def transpose(matrix)
matrix[0].zip *matrix[1..-1]

It’s the little things that make me like this language so much.

Update: I forgot the asterisk before matrix[1..-1] in the above method.


Summing it up

February 24, 2007

Today, I had a list of integers, and I wanted to sum it up. I guessed that I should write a script in Ruby, to make sure it would get done within 2 minutes. So I fired up my editor, and wrote the following script:

sum = 0 ;
$stdin.each do |line|
puts sum

Pretty straightforward. I’d rather had written the script in Haskell, but I figured I needed to get things done. This evening I tried the same thing in Haskell, but to I was surprised: it was even quicker and more straightforward than the Ruby version! Here it is:

main = interact $ show . sum . map read . lines

If you’d like more of these tiny tools, see Haskell Unix Tools.


My Evolution as a Haskell Programmer: Factorial with Arrows

February 19, 2007

A couple of years ago Fritz Ruehr wrote a great article about The Evolution of a Haskell Programmer. It was written in 2001, when I was still in high school, some years away from being introduced to the beautiful Haskell programming language.

Currently, I’m following a course on Advanced Functional Programming at the Utrecht University. One of the advanced topics tought in that course is about Arrows. Arrows are an abstraction of computations, just like Monads, but even more general and pretty nice to define stream functions with (useful for defining logical circuits, for example). I’m still trying to get my head fully around it, but so far I understand it enough to add a new part to the evolution (a missing link!): the factorial function defined with arrows.

I will present the code below and sparsely comment on it. Most of the code is actually from the Advanced Functional Programming lecture.

-- We need this library 
import Control.Arrow        

-- Define a type for stream functions, from one list to another 
newtype SF a b = SF { runSF :: [a] -> [b] }      

-- Define the Arrow functions for the SF type.  Once you've 
-- defined these three, you'll get a lot of other functions for 
-- free. 
instance Arrow SF where 
  arr f = SF (map f) 
  SF f >>> SF g = SF (f >>> g) 
  first (SF f) = SF (unzip >>> first f >>> uncurry zip)      

-- arr   lifts a function to the arrow domain 
-- >>>   combines (connects) two arrow functions 
-- first only applies the function to the first part from a 
--       tuple      

-- See the http://www.haskell.org/arrows for more 
-- information and some nice graphics, which will help 
-- understanding.

Okay, so far, so good. By defining the ‘first’ and ‘>>>’ functions, we get an ‘&&&’ combinator for free, which we will use in our final definition. For example: ‘f &&& g’ can be understood as accepting and input x, then applying both f and g to it, resulting in the output of a tuple of the results. In short, the type of ‘&&&’ is ‘Arrow arr => arr a b -> arr a c -> arr a (b, c)’.

-- The type of loop is (ArrowLoop arr) => arr (a, c) (b, c) -> 
-- arr a b.  A loop makes a function from 'a' to 'b', while 
-- 'looping' a 'c'. 
instance ArrowLoop SF where 
  loop (SF f) = SF $ \\as -> 
    let (bs,cs) = unzip (f (zip as (stream cs))) 
    in bs      

-- Note in the definition that cs is defined recursive(!)  This 
-- is really where the usefulness of Haskell's lazyness kicks 
-- in.  Although, because zip and unzip are both strict, we 
-- have to help it a little, by defining a helper function 
-- stream.      

stream :: [a] -> [a] 
stream ~(x:xs) = x:stream xs      

-- The ~ in the pattern makes the pattern matching irrefutable, 
-- which means that the pattern will not be interpreted but 
-- assumed to be correct.

Well, with that out of the way we can get to the good stuff. We just need two simple helpers to modify the stream.

-- 'Delays' a stream by prepending an element.  This can be 
-- used to initialize a stream _before_ the input is read. 
-- We're going to need this to use that nasty loop above. 
-- Remember, the c was defined recursive, without 
-- initialization. 
delay :: a -> SF a a 
delay x = SF (x:)      

-- Takes an input and muliplies it.  It 'simply' lifts an 
-- uncurried (*) to the arrow domain. 
-- Example (try it yourself): mul (6,7) = 42 
mul :: Arrow arr => arr (Integer, Integer) Integer 
mul = arr (uncurry (*))

Okay, now, the basic idea is to supply a stream function with the list of integers and then all we have to do is multiply the result of the first item with the second and multiply that result with the third, etc. Aha, that’s easy, we can just use the loop for that. The only thing we need is in initialization value to start the multiplying with. For this we use the delay. Schematicly, our plan looks like the following picture.

Factorial Arrows

You can clearly see how the loop works while the input and the output of the whole is still a single stream. The dot in the image where the output of ‘mul’ splits is actually the ‘&&&’ combinator. The code then looks like this.

facSF :: SF Integer Integer 
facSF = loop (mul >>> (arr id &&& delay 1))

Pretty clean, eh? Only thing left is a nice wrapper to run this thing.

-- Using Integers so that for large numbers (and factorials 
-- tend to get really large fast) it still produces nice 
-- output.  Try 'fac 420' for example. 
fac :: Integer -> Integer 
fac x = runSF facSF [1..x] !! fromInteger (x - 1)

This concludes our fun with Arrows. Viva la evolucion!