BAM Weblog

Learn Nintendo DS a Haskell

Brian McKenna — 2011-07-10

This weekend was AusHac 2011. I spent my time getting Haskell to compile to the Nintendo DS.

I remember reading a while ago about someone using JHC to compile a Haskell executable for the iPhone. JHC is a Haskell compiler that outputs fairly sane C code. I figured that it’d be fairly easy to get it to output code to work with devkitPro.

I had a quick version of this project working in December but I lost the patches and wanted to make a better version.

After a days work I had something compiling and I spent another day playing around with it. I think I created the world’s most annoying Haskell program:

It is much more annoying running on a physical DS:

I’ve uploaded the binary for people to try out. I’ve put the example project up on Bitbucket. The main Haskell for the example is:

printFreq freq = do
  consoleClear
  print freq

setSound sound freq = do
  soundSetFreq sound freq
  printFreq freq

keyLoop sound = do
  x <- keyboardUpdate
  scanKeys
  if x > 0 then do
    setSound sound $ x * 100
    putChar $ chr x
  else if isTouching then do
    if getTouchY < 110 then do
      setSound sound $ getTouchY * 100
      print getTouchY
    else
      return ()
    r <- randomRIO (0, 31)
    oamMainColor r 0 0
    oamMainSet getTouchX getTouchY
  else
    return ()

  swiWaitForVBlank
  oamMainUpdate
  keyLoop sound

main = do
  consoleDemoInit
  keyboardDemoInit
  keyboardShow
  soundEnable
  sound <- soundPlayPSG dutyCycle_50 10000 127 64
  oamMainInit
  keyLoop sound

To compile you have to setup devkitARM with my patch to libnds. You then need to setup JHC with my DARCS patch. I’ve forwarded the patches on so hopefully it will just work in the future!

Before this project, it was possible to run Hugs on the DS. While I think that is really awesome, I took the JHC approach for a few reasons:

  1. I couldn’t figure out an easy way to access C libraries from Hugs.
  2. I wasn’t sure how to make Hugs jump straight to executing custom Haskell code.
  3. Hugs is interpreted. I had a feeling that compiling to C and using GCC would give better performance.

Although the above example code is fairly ugly, I’m very confident that a nice DSL could be created for writing games. I’d love to see this happen.

Please enable JavaScript to view the comments powered by Disqus.