talkingCode

Archive for the haskell category

Pixmap, Pixbuf and memory lane

posted by codders in code, gtk, haskell

So how’s the Haskell project going? So far, so good. When I last wrote, I’d managed to load a “Hello World!” GUI for my application. Since then I’ve managed to parse up some content and render it to the screen. Current revision is 121ed7f2.

Antediluvian file formats

The project, in case you’ve not been following on github, is to resurrect a long-since abandoned game. This game was released as a cover disk on an Amiga magazine back in “the day” and the code has since been made available by the authors (in 68000 assembly), ported to BlitzBasic and (abortively) ported to C++/SDL.

The maps for the BlitzBasic game were stored as tile maps. Each game level combines a tile set and a map to place the tiles on the screen. For additional kicks, some of the files are compressed under a scheme called “BPCK” which involves fairly simple run-length encoding. The code to parse up those files was… err… relatively straightforward to write although I did have some issues with bit-order and palette mapping.

Tiles as Pixbufs

The tiles are stored as sequences of nibbles mapping pixels on to a 16-colour palette. In order to draw these, I extracted the RGB for the nibbles and inserted that 3-byte-per-pixel sequence into a pixmap (this is the source):

buildTile :: [BPCK.PaletteEntry] -> BPCK.Gliph -> IO Pixbuf
buildTile palette g = do
    let gData = BPCK.gliphData g
    buf <- pixbufNew ColorspaceRgb False 8 gliphX gliphY
    pbData <- (pixbufGetPixels buf :: IO (PixbufData Int Word8))
    rowStride <- pixbufGetRowstride buf
    chan <- pixbufGetNChannels buf -- Hopefully this is 3 (R,G,B)
    bits <- pixbufGetBitsPerSample buf -- Hopefully this is 8
    doFromTo 0 (gliphX - 1) $ \y ->
      doFromTo 0 (gliphY - 1) $ \x -> do
        let pixbufoffset = x*chan + y*rowStride
        let gliphOffset = fromIntegral $ x + y*gliphX
        let paletteIndex = B.index gData gliphOffset
        let thiscolor = palette !! fromIntegral paletteIndex
        writeArray pbData (pixbufoffset) (fromIntegral $ BPCK.red thiscolor)
        writeArray pbData (1 + pixbufoffset) (fromIntegral $ BPCK.green thiscolor)
        writeArray pbData (2 + pixbufoffset) (fromIntegral $ BPCK.blue thiscolor)
    return buf
    where gliphX = BPCK.gliphWidth g
             gliphY = BPCK.gliphHeight g

Maps as Pixmaps

The difference between a pixbuf and a pixmap is, as I understand it, that a pixbuf is an X-client side block of data into which you can load pixel information and a pixmap is an X-server side drawable (in the GTK sense) object. Pixbuf is more like a brush for painting, and Pixmap is an off-screen canvas. So to build my map I blatted the tile pixbufs on to a pixmap:

createTiledPixmap :: BPCK.ParsedImage -> BPCK.ParsedTileMap -> IO Pixmap
createTiledPixmap tileSet tileMap = do
    putStrLn $ "Building tile pixmaps"
    tiles <- tilesFromImageData tileSet
    let tileCount = length tiles
    putStrLn $ "Creating new pixmap " ++ show totalWidthPixels ++ " x " ++ show totalHeightPixels
    pixmap <- pixmapNew (Nothing :: Maybe DrawWindow) totalWidthPixels totalHeightPixels (Just 24)
    gc <- gcNew pixmap
    doFromTo 0 (tilesHigh - 1) $ \iy ->
      doFromTo 0 (tilesAcross - 1) $ \ix -> do
        let tileIndex = ix + (iy * tilesAcross)
        let tileId = (min (fromIntegral (BPCK.tileMap tileMap !! tileIndex)) tileCount) `mod` tileCount
        let curX = ix * tileSizePixels
        let curY = iy * tileSizePixels
        postGUIAsync $ drawPixbuf pixmap gc (tiles !! tileId) 0 0 curX curY tileSizePixels tileSizePixels RgbDitherNone 0 0
    return pixmap
    where tileSizePixels = BPCK.gliphSize tileSet
             tilesAcross = BPCK.tilesAcross tileMap
             tilesHigh = BPCK.tilesHigh tileMap
             totalWidthPixels = tileSizePixels * tilesAcross
             totalHeightPixels = tileSizePixels * tilesHigh

Results

The finished article looks a bit like this:

Screenshot
or this:

Screenshot
and pressing the space bar cycles through the maps on account of this:

onKeyPress app (\x@(Key { eventKeyName = name,
                              eventKeyChar = char }) -> do
    case char of
      Just ' ' -> do
        putStrLn $ "Switching map"
        currentState <- readIORef mapStateRef
        nextState <- nextMapState currentState
        writeIORef mapStateRef nextState
        drawWin <- widgetGetDrawWindow canvas
        gc <- gcNew drawWin
        (width, height) <- drawableGetSize drawWin
        postGUIAsync $ drawDrawable drawWin gc (renderedMap nextState) 0 0 0 0 width height
      Just c -> putStrLn $ "Press " ++ name ++ "('" ++ [c] ++ "')"
      Nothing -> putStrLn $ "weird key: " ++ name
    return (eventSent x))

Conclusions

I’m now a lot more comfortable with Haskell and think I’ve mastered the “word-for-word translation of imperative to pseudo-functional” style. The file parsing code I’ve written performs like a dog on account of that, but it’s not on a critical path for anything. One thing that has struck me is how easy it is to refactor Haskell code (as long as you use hanging ‘do’s to avoid formatting upsets). So I’ll stick at it and see if I can’t finish this project inside of a year.

Why not SDL?

FYYFDANSEIC, etc.

GTK, Glade, Haskell and gnome_program_init()

posted by codders in c, code, gtk, haskell

So. I finished the book (at length, and to be fair I mostly skimmed the last chapters), which means it’s time for me to start actually writing Haskell code. I thought I’d start with a simple GUI app, but it turned out not to be quite so simple.

I’ve put the code that I’m working on up on GitHub because that’s what all the cool kids are doing. My project is called GP3 for reasons that ought eventually to become clear. HEAD at time of writing is 7b01940

Glade
Glade is a GTK UI designer. I won’t go in to a lot of detail – there’s been plenty written about it. What I will say, though, is that at version 3, you can often find yourself creating unexpected dependencies for your program by using the more complex widgets. I unwittingly picked something from the “GNOME User Interface” toolbox, which has a Glade class of “GnomeApp”. This includes a “BonoboDock” and a “BonoboDockItem”.

Launching your app
Borrowing heavily from the book, here’s part of the code I was using to launch my app:

main :: FilePath -> IO ()
main gladepath =
  do
    unsafeInitGUIForThreadedRTS
    timeoutAddFull (yield >> return True) priorityDefaultIdle 100
    gui <- loadGlade gladepath
    connectGui gui
    windowPresent (mainApp gui)
    mainGUI

gnome_program_init()
Having made the mistake of using a GNOME-UI widget, I saw this when I ran my app:

GnomeUI-ERROR **: You must call gnome_program_init()
          before creating a GnomeApp

This is because my Glade UI requires libgnomeui to be initialised. To make matters worse, libgnomeui isn't linked by default in to Gtk2Hs. In my limited understanding of Haskell and Gnome, there are two options at this point. One is to import the gnome_program_init function from libgnomeui over FFI. The other is to write a C program to wrap a call to gnome_program_init and re-export a simpler function for you to import over FFI. I chose the latter option:

// gtk_docker.c
#include 

void do_gnome_init()
{
  static char **argv = NULL;
  if (argv == NULL)
  {
    argv = malloc(2);
    argv[0] = "gtk_docker";
    argv[1] = '\0';
  }
  gnome_init("my-app", "my-version", 1, argv);
}

... and a header file

// gtk_docker.h
void do_gnome_init(void);

Astute observers will see that this is a bit of a cheat. GnomeUI wants the command line arguments that were passed to the executable. It would be possible, but irritating, to arrange this. I couldn't easily divine how to pass an array of CStrings over FFI, so I wimped out. Also, I'm not technically calling gnome_program_init - this call appears to be deprecated in favour of gnome_init, and the latter call also silences the error message.

Compilation
We haven't solved the compilation problem yet. The compiler still needs to know where to find gnome.h and its included headers, and needs to know where to find the associated libraries for linking. There are good ways and bad ways to solve this problem... here's a bad way:

#Makefile
LDFLAGS = -lgnomeui-2 -lcairo -lglade-2.0
CFLAGS = -I/usr/include/libgnomeui-2.0 -I/usr/include/gtk-2.0/ \
              -I/usr/include/cairo/ -I/usr/include/glib-2.0/ \
              -I/usr/lib/glib-2.0/include/ \
              -I/usr/include/pango-1.0/ \
              -I/usr/lib/gtk-2.0/include/ \
              -I/usr/include/atk-1.0/ \
              -I/usr/include/libgnome-2.0/ \
              -I/usr/include/libbonobo-2.0/ \
              -I/usr/include/libgnomecanvas-2.0/ \
              -I/usr/include/libart-2.0/ \
              -I/usr/include/libbonoboui-2.0/ \
              -I/usr/include/gnome-vfs-2.0/ -Werror -Wall

GHCC=ghc

default: gp3

gp3: gtk_docker.o GP3Main.hs GP3GUI.hs
        $(GHCC) --make $(LDFLAGS) $^

clean:
  rm -f *.o *.hi GP3Main

The real answer probably involves GNU AutoTools for the C toolchain or some craziness with Cabal. I'm sure I'll get round to that :)

Calling the function
Now to clear that error message. We just need to...

{-# LANGUAGE ForeignFunctionInterface #-}

foreign import ccall unsafe "gtk_docker.h do_gnome_init"
      c_gnome_init :: IO ()

and

main :: FilePath -> IO ()
main gladepath =
  do
    unsafeInitGUIForThreadedRTS
    c_gnome_init
    ...

and we're done.

Portability
Linking libgnomeui probably makes my code a lot less portable. Hard-coding the include paths certainly does. Fortunately I don't have to care about other users just yet, and I'm unlikely ever to care about other platforms :)

Haskell, GTK and Multi-Threading

I have been working on an application in Haskell, using Gtk2Hs for the user interface. Now, you normally want a graphical user interface (GUI) to be responsive, so you avoid doing tasks that take a long time in the thread that handles the GUI. Instead, your main computation happens in other application threads, and all that happens in the GUI thread is updating of interface elements. It turns out that there are several issues that come up when you mix Haskell, GTK and multiple threads, which is why this post is here.

Part 1: The GTK event loop

Most programs that use Gtk2Hs first do all the GUI-related initialization, and then execute the mainGUI computation. This is actually a loop that processes GTK-related events until the user quits the program. Because of the way thread switching works in Haskell, a thread executing a loop like that will not let any other “lightweight” threads run. (Lightweight threads are threads created using the forkIO computation.) One frequently suggested way to solve this problem is to make the GTK event loop periodically yield to any other Haskell threads by adding the following to your GUI initialization code:

timeoutAddFull (yield >> return True) priorityDefaultIdle 100

Note that this is only an issue when all lightweight Haskell threads run on top of a single operating system thread, as in the single-threaded RTS of GHC. If Haskell threads are allowed to run on multiple OS threads, then yielding is not necessary.

Part 2: GTK thread safety

It turns out that that GTK (the C library wrapped by Gtk2Hs) is not thread-safe. What this means is that all modifications of GTK state must happen from a single OS thread, which also must be the same thread that is executing the GTK event loop. If all Haskell threads are run on top of a single OS thread, this is easy to ensure. However, if you use a system where lightweight threads may be mapped to different OS threads (such as in the multi-threaded RTS in GHC), care must be taken when accessing a GUI. Essentially, application threads need to put GUI modification events onto a queue, with the thread that runs the GTK event loop processing the events from that queue. Fortunately, Gtk2Hs comes with such a queue built-in; you can use the postGUI functions to give the event loop blocks of IO to execute.

Note that, by default, Gtk2Hs will produce a warning when running under the GHC multi-threaded RTS. To get rid of this, use unsafeInitGUIForThreadedRTS instead of the usual initGUI to perform GTK initialization. The “unsafe” part of the computation name signifies that you are aware of the requirement to only modify GTK state from the correct OS thread.

Part 3: Deconstructing the GTK event loop

There might come a time when you want to do something more complicated than the above solutions allow. In such a case, you can actually substitute the mainGUI event loop with your own. Gtk2Hs provides functions that will process a single event at a time off the GTK event queue. Put these in a loop, sprinkle with your custom logic (such as pulling events off multiple queues), and you’re done!

Context

This was written with the GHC environment in mind. Other Haskell compilers and/or interpreters may differ in their implementations.

Coding style, Haskell

posted by codders in haskell, rant

I finished chapter five of the Haskell book I’m reading last night, and the bits of it are starting to make sense. I was doing some of the exercises and managing to write functions that compiled first time – I’m all about the small victories.

What I’m enjoying most about the book, though, is that as well as teaching the language it does a good job of teaching some of the culture. A lot of writing good software is about making the most effective use of the tools a language provides and that usually only comes with time and experience. The book helps, though, providing gentle prods in the right direction:

Many tail recursive functions are better expressed using list manipulation functions like map, take, and filter. Without a doubt, it takes some practice to get used to using these. What we get in return for our initial investment in learning to use these functions is the ability to skim more easily over code that uses them.

The reason for this is simple. A tail recursive function definition has the same problem as a loop in an imperative language: it’s completely general, so we have to look at the exact details of every loop, and every tail recursive function, to see what it’s really doing. In contrast, map and most other list manipulation functions do only one thing; we can take for granted what these simple building blocks do, and focus on the idea the code is trying to express, not the minute details of how it’s manipulating its inputs.

In the middle ground between tail recursive functions (with complete generality) and our toolbox of list manipulation functions (each of which does one thing) lie the folds. A fold takes more effort to understand than, say, a composition of map and filter that does the same thing, but at the same time it behaves more regularly and predictably than a tail recursive function. As a general rule, don’t use a fold if you don’t need one, but think about using one instead of a tail recursive loop if you can.

As for anonymous functions, they tend to interrupt the “flow” of reading a piece of code. It is very often as easy to write a local function definition in a let or where clause, and use that, as it is to put an anonymous function into place. The relative advantages of a named function are twofold: we’re not confronted with the need to understand the function’s definition when we’re reading the code that uses it; and a well chosen function name acts as a tiny piece of local documentation.

… and they’ve not once suggested I write any comments yet. Woot :)

The Book:

http://book.realworldhaskell.org/beta/

Chapter 5:

http://book.realworldhaskell.org/beta/fp.html

More Haskell fun

posted by codders in code, haskell

Define a tree type that has only one constructor, like our Java example. Instead of the Empty constructor, use the Maybe type to refer to a node’s children.

Fair enough. How bout this?

data MaybeTree a = MaybeNode (Maybe (a (MaybeTree a) (MaybeTree a)))

It’s a real type. I can even make real values in the type:

maybeTree = MaybeNode (Just ("fish",
             (MaybeNode (Just ("left",
                               (MaybeNode Nothing),
                               (MaybeNode Nothing)))),
             (MaybeNode (Just ("right",
                               (MaybeNode Nothing),
                               (MaybeNode Nothing))))))

Buuut I can’t print them. Because I don’t derive Show. If I try to derive Show:

    No instance for (Show (a (MaybeTree a) (MaybeTree a)))
      arising from the 'deriving' clause of a data type declaration
                   at working.hs:(51,0)-(52,30)
    Possible fix:
      add an instance declaration for
      (Show (a (MaybeTree a) (MaybeTree a)))
    When deriving the instance for (Show (MaybeTree a))

That’s fair enough. And GHC’s even provided me with a hint. So I just… err… instance Show something, right? Wrong :(

Let’s write the show function for my tree type:

showTree (MaybeNode Nothing) = "empty"
showTree (MaybeNode (Just (a, b, c))) = "Node: " ++ (show a) ++
              ", Left: " ++ (showTree b) ++
              ", Right: " ++ (showTree c)

s’all good. But the type of that function?

showTree :: (Show t) => MaybeTree ((,,) t) -> [Char]

See that ((,,) t)? That’s the badness.

*Main> :kind (,,)
(,,) :: * -> * -> * -> *

Yeah. So it’s a tuple that has three type variables. Fun. Now I’m pretty sure that I ought to be able to define an instance of Show for my type, but I can’t for the life of me work out what the syntax is going to be

instance (Show a) => Show (MaybeTree ((,,) a)) where
       show t = showTree t

working.hs:58:0:
    Illegal instance declaration for `Show (MaybeTree ((,,) a))'
        (All instance types must be of the form (T a1 ... an)
         where a1 ... an are distinct type *variables*
         Use -XFlexibleInstances if you want to disable this.)
    In the instance declaration for `Show (MaybeTree ((,,) a))'

??? How about

instance (Show a) => Show (a, MaybeTree a, MaybeTree a) where
        show t = showTree t

working.hs:61:40:
    Kind mis-match
    Expected kind `* -> * -> *', but `a' has kind `*'
    In the type `MaybeTree a'
    In the type `(a, MaybeTree a, MaybeTree a)'
    In the type `(Show a) => Show (a, MaybeTree a, MaybeTree a)'

Any answers much appreciated, glorious lazyweb. I’m adding this to the list of exercises in the book that you can’t answer at the point you’ve reached in the book (this is chapter 4). Even after reading around about types and kinds and other peoples’ use of instance, I’m clueless.

And changing my type to be something sane doesn’t count. If it’s not possible to Show my type, I’d like to know why :)

Update:
After much discussion with sffubs and sos, it seems the only reasonable thing to do is to

{-# LANGUAGE FlexibleInstances #-}
instance (Show t) => Show (MaybeTree ((,,) t)) where
  show = showTree

We’re not quite sure what Flexible Instances are, but it seems that’s what’s needed to make this datatype work. The real answer is obviously not to use a crazy datatype:

data FooTree a = Maybe a ((FooTree a), (FooTree a)) deriving (Show)

Thanks both.

Getting started with Haskell… still

posted by codders in code, haskell

I can’t help but think there’s a bit of a gap in the market for introductory texts on Haskell. I say this in part because, at time of writing, if you google (hah! I’m using it as a verb! Trademark that!) “Getting Started Haskell”, you might end up here =/

I’d resolved to try getting started again on account of continuing to hear people rave about the language, so last night I did what I always do when learning something new – I googled “Getting Started X”. I found this awesome e-book / blog:

http://book.realworldhaskell.org/beta/index.html

It’s very well written (if a little rough round the edges – beta is the word), but I still think the learning curve presented is a _little_ steep for simpletons like myself. Bear with me while I expose my ignorance.

We’re using GHC. GHC is recommended by the book, it’s recommended by Don (who is indescribably leet: http://cgi.cse.unsw.edu.au/~dons/blog/), and it’s recommended by my n-sim colleagues (who mostly are, except for me: http://www.n-sim.com).

# apt-get install ghc6
# ghci
GHCi, version 6.8.2: http://www.haskell.org/ghc/  : ? for help
Loading package base ... linking ... done.
Prelude>

aaah. Prelude. Don’t I feel at home. In fact I don’t – this is all pretty weird, but working through the first couple of chapters of the book was fun. Walk with me a while…

Type Porn
If types don’t excite you, this probably isn’t the language for you. But they should; they’re awesome.

Prelude> :set +t
Prelude> 1337
1337
it :: Integer

In GHCI (interactive GHC interpreter), setting “+t” makes the interpreter print the type of whatever you’ve just evaluated. Technically, it prints the type of “it” – the special value in to which your last evaluated expression is loaded (there is no spoon, there are no variables). I know what “1337″ is, I know what “it” is, but what’s “Integer”?

Prelude> :info Integer
data Integer
  = GHC.Num.S# GHC.Prim.Int#
  | GHC.Num.J# GHC.Prim.Int# GHC.Prim.ByteArray#
        -- Defined in GHC.Num
instance Enum Integer -- Defined in GHC.Num
instance Eq Integer -- Defined in GHC.Num
instance Integral Integer -- Defined in GHC.Real
instance Num Integer -- Defined in GHC.Num
instance Ord Integer -- Defined in GHC.Num
instance Read Integer -- Defined in GHC.Read
instance Real Integer -- Defined in GHC.Real
instance Show Integer -- Defined in GHC.Num

ooo… fancy. What does that all mean? Well, I’m only on chapter 3, but in my simplistic Object Oriented view of the world, we’re effectively saying that Integer implements the interfaces Enum, Eq, Integral, Num, Org, Read, Real and Show (but the truth is a little more involved).

Prelude> :info Enum
class Enum a where
  succ :: a -> a
  pred :: a -> a
  toEnum :: Int -> a
  fromEnum :: a -> Int
  enumFrom :: a -> [a]
  enumFromThen :: a -> a -> [a]
  enumFromTo :: a -> a -> [a]
  enumFromThenTo :: a -> a -> a -> [a]
        -- Defined in GHC.Enum
instance Enum Integer -- Defined in GHC.Num
instance Enum Float -- Defined in GHC.Float
instance Enum Double -- Defined in GHC.Float
instance Enum Bool -- Defined in GHC.Enum
instance Enum Ordering -- Defined in GHC.Enum
instance Enum Char -- Defined in GHC.Enum
instance Enum () -- Defined in GHC.Enum
instance Enum Int -- Defined in GHC.Enum

You kind of have to be comfortable with looking at types of the form:

a -> a -> a -> [a]

“enumFromThenTo” obviously takes three values and returns a list of values. (The joy of types, right? You know what it does by what its type is.) Moreover, we can see that it’s defined for the instances Integer, Float, Double, Bool, Ordering, Char, () and Int.

Prelude> enumFromThenTo 1 2 8
[1,2,3,4,5,6,7,8]
Prelude> enumFromThenTo () () ()
[(),(),(),(),(),()^CInterrupted.

and we can type functions too:

Prelude> :type fst
fst :: (a, b) -> a

What does that one do? There's only one thing it can do! Yes, I know, that's practically pornographic.

The exercise
"Write a function lastButOne, that returns the element before the last."

Trivial, right? A five year old could do it. Well, excuse me while I have a quick flashback to ML ticks (PDF) and rock gently back and forth in the corner. You have to bear in mind that, at this point in the book, we don't know there's a 'length' function in Prelude, we've not been taught pattern matching or case statements, and we're still simplistically minded imperative programmers. So naïvely, the best we might be able to do is:

-- in add.hs
count n [] = n
count n xs = count (n+1) (drop 1 xs)

myLastButOne xs = head (drop ((count 0 xs) - 2) xs)

Prelude> :load add.hs
[1 of 1] Compiling Main             ( add.hs, interpreted )
Ok, modules loaded: Main.
*Main> myLastButOne [1,2..10]
9

Repeat after me… “ewww”. And even to do that, I’ve had to use mysterious pattern matching which hasn’t been explained at that point in the book. Now, we could assume that a resourceful reader might find the ‘length’ function:

myLastButOne xs = head (drop ((length xs) - 2) xs)

But that’s still pretty unsatisfactory. For all I know, length is O(n) in the length of the list, so I’ll be going down the list twice. I daren’t imagine what Don would say. Even if it’s O(1), it doesn’t feel right. After a bit of head scratching and syntax guessing, I came to:

lastButOne (h:t) = case t of
                       (a:[]) -> h
                       (a:b) -> lastButOne t

which, for me at least, feels a little better. But I don’t know it’s right. I’m welcoming any pointers here. Now obviously for the “Find the last but nth item”, going down the list twice is looking less unattractive:

myLastButN n xs = head (drop ((length xs) - (n+1)) xs)

It’s still not great though. Would that I could list[-n]. But that’s not the point.

Summary
I’m determined to learn more Haskell and continue to expose my ignorance on this blog. Any pointers to good docs are welcome – “Haskell for simpletons”, that sort of thing. Meantimes I’ll continue to read the book. My stretch goal is to understand the things written on Don’s blog and on the following:

Conal Elliott:
http://conal.net/blog/

Kenn Knowles:
http://www.kennknowles.com/blog/

Getting started with Haskell

posted by codders in code, haskell

All the cool kids, it seems, are using Haskell these days. Or at least, the two or three people with whom I talk about software on a regular basis. Functional programming is fun. It makes you think a little differently about the world, and serves as a decent substitute for a unicorn chaser if you’ve been writing PHP all day.

I remember almost the first snippet of code we saw on our computer science course was the following to count the number of items in a list:

count [] = 0
count (x:xs) = 1 + count(xs)

which, for a guy who’d only ever really written code in BASIC before starting the course, was a bit of an eye opener. I think it was probably three or four lectures in before we had to work out the code for printing out all the permutations of a list:

> permute [1,2,3]
[[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]]

After much blood, sweat, and tears we’d eventually come to the realisation that:

insert x [] = [[x]]
insert x (y:ys) = (x:y:ys) : map (\z -> y:z) (insert x ys)

permute [] = [[]]
permute (x:xs) = concat (map (insert x) (permute xs))

would suffice (where concat flattens a list and map has the usual meaning). At first glance, it all looks pretty daunting, but after a while one comes to understand what it means for the type of map to be (a -> b) -> [a] -> [b], and starts to appreciate the compact elegance of the code that’s produced in functional programming.

Ugly implementation details? You betcha…

apt-get install hugs
apt-get install haskell98-tutorial
cat > hello.hs <<END
#!/usr/bin/runhugs +l
main :: IO()
main = putStr "Hello World!\n"
END
chmod 755 hello.hs
./hello.hs

(N.B. hugs with the ‘+l’ switch is sensitive about filenames. Non ‘.hs’ files require lines of Haskell to begin ‘>’). It’s often more comfortable to develop these things interactively. Booting into a hugs session and typing

> :load hello.hs

will import the functions defined in hello.hs into your session.

Over the coming weeks, I hope to be honing my skills and infuriating my coworkers by replacing bits of critical infrastructure with Haskell scripts. I’ll let you know how that goes.

Recent Posts
Recent Comments
About Us
jp: works like a charm! thanks!...
Blake: Check this out: http://bugs.adobe.com/jira/browse/SDK-28016...
Boydell: Wow. That was it. You are the only one that had it figured out, and I looked at many...
mark van schaik: thanks! was using a beta SDK version for a production app, which stopped working over...
Sebastian: Steve, I find most asynchronous programming to be incredibly painful. Haskell's appro...

This is the personal blog of a professional software engineer. This site and the views expressed on it are in no way endorsed by the RIAA.