← Back

Learning functional programming with game development - OCaml & Haskell

2026-09-24 › 11 min ›

I have been in the programming industry for coming up to a decade now, yet in all that time, I have never been exposed to functional programming paradigms apart from list comprehension in any meaningful way.

  • .filter
  • .forEach
  • .map

are all well-estabilished functional patterns that exist in almost all languages under one name or another.

But some time ago I decided I want to pickup and delve into majority functional languages. So I decided to pick up a small game development project which I want to implement in purely that language. For this, my initial list of languages was:

  • Haskell
  • OCaml
  • Roc
  • F#
  • Lisp (SBCL)

I am relatively familiar with Lisp, or rather Elisp due to Emacs, and had some contact points with OCaml as well.

So initially I thought, why not delve into Haskell? I think it is reasonable to say that it takes the cake as the most predominant grandfather of functional programming nowadays, most newer programming language Rust, Swift, Scala, Clojure took inspiration from Haskell in some way or another, so it can’t be that bad?

To evaluate Haskell, and the other contenders, I set a goal for myself: implement a crude Pong clone, this seemed like a reasonable goal, Pong is simple enough where 500 lines of code should suffice, and the logic is easy to write.

Haskell

So I set out, first I looked for Raylib bindings, the easiest way of getting a quick rendering loop, with tons of documentation and sane defaults, and of course, because Raylib is so well known at this point, there are bindings to it in Haskell.

The main loop proved unspectacular, in true functional fashion, it naturally became a recursive function instead of the common imperative while (WindowShouldClose () == false) { ... } loop.

1 2 3 4 5 6 7 8 9 10 11 12
runGame :: Game -> IO ()
runGame lastGame = do
  game' <- updateGame lastGame
  drawGame game'
  exit <- gameOver game'
  if exit then pure ()
  else gameLoop game'

main :: IO ()
main = do
  let game = initGame
  runGame game

But a pong game without inputs is not really a pong game.. And this is where the trouble started.

If we introduce input, we introduce side-effects to the game simulation (updateGame), this makes the simulation non-deterministic. While I agree with side effects and non-determinism being bad, the way I had to solve this in Haskell quickly proved itself to be a nuisance.

For input this is still fine, runGame is already non-deterministic, because it draws to the screen, so we just have to

1 2 3 4
runGame lastGame = do
  input <- pollInputs
  game' <- updateGame input lastGame
  -- ...

Okay, that is still reasonable, it also makes testing the game easy.

We can reduce any given bug down to a defined game state and run the simulation with the mock inputs to get to the invalid state, adding a test suite for that exact issue and prevent regressions.

… But as soon as we introduce more non deterministic state, we really start churning out a lot of duplicate and annoying code.

Say the round is over, and the ball takes a random direction to fly, this warrants another parameter to updateGame, now we are already looking at

1
updateGame :: StdGen -> Input -> Game -> Game

Do not get me wrong, I genuinely see the upside of doing it this way, I am on the side of the aisle that prefers added explicit over implicit behaviour, and even randomness can be a source of incorrect behaviour, which this makes much easier to track / prevent from happening altogether.

But add onto that that we can not name the parameters, we quickly start writing code that makes sense at the moment, but devolves into a almost undecipherable mess when we do not touch it for a while.

Balls should bounce off of the walls, so we need the bounds of the playable area when updating the paddles and ball.

1
updateGame :: StdGen -> Dimensions -> Input -> Game -> Game

Now we already have

1 2 3 4 5
runGame lastGame = do
  input <- pollInputs
  rng <- getStdGen
  dim <- (getScreenWidth (), getScreenHeight ())
  game' <- updateGame rng dim input lastGame

Preventing this requires either:

  1. Virally infecting the codebase with the IO monad, and losing the advantage functional programming grants us
  2. Offloading those fields into the Game record, updating it once per frame. (Not very functional, and an ugly solution)

In any case, it may, depending on the size of our project thus far, require changing lots of other places in the code, depending on what we are doing.

Ultimately, after finishing this initial prototype of pong (source code on codeberg), I decided to checkout OCaml for this recreational game dev project again.

… But I do have to note, that even though in the process of writing this pong clone, I got frustrated by the above points, writing down my thoughts on it like this makes it seem more of a reasonable trade-off than a major deal-breaker. But the prop-drilling is really annoying if the application grows big enough where a previously pure function now requires a call to a non pure version, and therefore requires us to dill up the callstack and introduce StdGen for every subsequent call…

Even though games are naturally non-deterministic, the benefit of explicitly having to hand down the unwrapped pure results of side-effects, such as reading input, warrants the pain of changing a few function invocations here and there.

Penultimately, I want to note that I am still unsure if it is possible to ship games in a reasonable amount of time in Haskell, its lazy and garbage-collected nature do make it difficult to estimate runtimes when on a tight frame budget, I will take it up again in the future.

OCaml

OCaml is, like Haskell, a predominantly function programming language, albeit with a much lamer name.

I tried dabbling in it in the past, but never wrote anything of much significance, as I struggled to understand Monads, and Lwt certainly did nothing here to help me further my understanding.

While OCaml is a functional language like Haskell, it mixes it with both selective mutability, some imperative control-flow primitives such as while and for, and even cool features first-class module support, and less cool features like object orientation Though this seems to have been superseded at large by module sig and first-class modules..

As a first order of business, I re-did the same game of Pong in OCaml, trying to adhere to functional standards where-ever possible and convenient.

And boy was it easier than Haskell, since OCaml is strictly evaluated, unlike Haskells lazy evaluation, it felt more natural to me, coming from a background of traditional imperative programming in C/C++.

The syntax is also much more approachable than Haskells. In Haskell, it feels to me that the community at large adores operators to an unreasonable amount, any best practice I looked up threw me down a deeper rabbit hole of having to understand operators like <$>, <>, <*>, …

So far, this has not been an issue in OCaml, while operator overloads are also possible here, they are used more sparingly, favouring names over cryptic operators.

Back to the topic, the same game loop in OCaml looks like this:

1 2 3 4 5 6 7 8 9 10 11
let rec loop game =
  if not (Raylib.window_should_close ()) then begin
    let game = tick_game game dt in
    draw_game game dt;
    loop game
  end

let () =
  setup ();
  let game = init_game () in
    loop game

The game state object still evolves from simulation step to simulation step, but since we can have side-effects in functions, tick_game itself can poll random numbers, the inputs, etc.

Overall, I got much further much quicker in OCaml than Haskell, though I also dropped the functional nature at multiple points in time to achieve this goal, fundamentally I now got to the point where I can confidently say that I think the purely functional approach like Haskells is better for correctness than what I did with this OCaml implementation.

Dune

Dune is OCamls build system, the cargo of the OCaml world, you fetch dependencies directy via it, run the application, run tests, compile it, etc.

And what a blessing dune is. It supports ppx, a stateful preprocessor that allows us to write custom syntax natively in OCaml (oh, what a blessing!), and even other niceties, take this example I have:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(rule
 (targets shaders.ml)
 (deps
  ../assets/basic.vert
  ../assets/basic.frag)
 (action
  (with-stdout-to %{targets}
    (progn
      (echo "let basic_vertex = {|")
      (cat ../assets/basic.vert)
      (echo "|}")
      (echo "")
      (echo "let basic_fragment = {|")
      (cat ../assets/basic.frag)
      (echo "|}")))))

(even Lisp-syntax, nice!)

The build system is powerful enough to be able to directly produce source files as above, embedding the vertex and fragment shader directly in the binary.

With C/C++ this is also possible, either via cmake, which would be a more verbose but quintessentially the same setup, or via the new C23 #embed preprocessor, though I am unsure about the compiler support as of this day.

It can also handle mono-repos very nicely, I liken the setup here to how it is done in Go for those familiar, splitting up responsibilities across multiple sublibraries.

1 2 3 4 5 6 7 8 9
lib/
  - {game,entity,systems}.ml
  - dune # (library)
bin/
  - main.ml
  - dune # (executable ..., depends on lib, renderer)
renderer/
  - {window,model}.ml
  - dune # (library, depends on Raylib)

Performance

Both Haskell and OCaml are perfectly fine choices for Pong, the logic is so short and concise, there is virtually no way of ever being constricted by the languages runtimes, even though both are garbage collected.

In the preliminary of this post, I mentioned a small recreational game project I wanted to take up, after my experience with Haskell and OCaml, I ultimately started this project with OCaml.

The downside of the functional paradigm is that we can not combine both unparalleled CPU runtime and functionality. We have to make compromises in one discipline or another, when I started out the project, I was worried I would somehow be able to choke so much out of the runtime, that the game would run at subpar performance.

This so far proved untrue.

Yeah, sure, OCaml and Haskell are both garbage collected language, and coming from a background where privately I wrote most of my software in C/C++, I took up a sceptic look on the garbage collector, worried that GC cycles would eat up many of the precious few milliseconds we have to complete a timestep.

But the reality proved that the runtime and garbage collector of atleast OCaml is capable of far more than I anticipated.

One of the first things I wrote in OCaml for this game is an Entity-Component-System For those unfamiliar, an Entity-Component-System, on a high level, translates into a strictly typed, almost SQLite-like data structure.

Entities (which would be a row) are created empty, and then annotated with Components (those would be columns; Position, Velocity, etc.).

For game logic, we then write systems (queries) that take a list of components our entity needs (NOT NULL), and perform operations on them.

True to the words of Donald Knuth, I did not factor in performance in my preliminary design, component storages were Lists instead of Arrays, no sparse keying, no archetypes, just a barely functional ECS implementation, and what can I say, it really surprised me.

Iterating on 100’000 entities, took 6ms, sure the senior engine programmer might now scoff and say that is laughable, EnTT is about 2 orders of magnitude faster https://github.com/abeimler/ecs_benchmark, but for a unoptimized mess that I call my implementation for this scope? More than fast enough. Consider that this is in a functional garbage collected language, suffice to say I was impressed.

The function pipeline operator also made it so nice to work with:

1 2 3 4
ECS.create
  |> add (module Position) { ... } world
  |> add (module Player)   { ... } world
  |> add (module Health)   { ... } world

But what I am really excited about is the DSL like querying syntax I can compose:

1 2 3 4 5 6 7 8 9 10
ECS.(
  query world
    |> require (module Damage)
    |> require (module Health)
    |> where (module Health) ((>=) 0)
    |> iter (fun entity world ->
      let health = get (module Damage) world entity in
      apply_damage damage entity;
    )
)

Adding a few more procedures, I can do this

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
ECS.(
  query world
    |> require (module Player)
    |> require (module Position)
    |> exclude (module Death)
    |> iter (fun entity world ->
      draw_player_model entity;
    )
)

ECS.(
  query world
    |> require (module Player)
    |> require (module Position)
    |> require (module Death)
    |> iter (fun entity world ->
      draw_player_tombstone entity;
    )
)

For a one-man project, I think this end-to-end implementation is top-notch, though likely less performant than the open-source implementations VLanvin/ECS and fccm/ocaml-enties (unverified. but looking at the code, my simple implementation is likely a bit faster than VLanvin/ECS)

Finally; I have gotten quite a few things to work in this OCaml game dev project of mine thus far, and think that the performance is fine-ish for what I already have. If it plays out as I expect it to, I will spent most of my frame budget waiting for the GPU anyhow, a few GC pauses here and there should be digestible.

A major pain I had with this project thus far has been the GUI, writing a good immediate mode UI is nigh impossible, so I rolled a custom retained solution, which has been okay so far, theres a few hitches here and there I need to iron out, but for anyone has been reading this far, I want to present and immortalise a library I came across just today, bonsai, while it prouds itself as a js_of_ocaml solution for writing HTML user interfaces, there is this extension bonsai_term to use bonsai even for TUIs, therefore it should be possible to use bonsai even with a custom rendering backend, such as Raylib. Worth having in mind!

F#, Roc and SBCL

The initial list of languages I wanted to evaluated also listed these ones, I have not gotten around to try them yet. Except SBCL

F# is a product of Microsoft, and I kinda want to avoid jumping on the Mono bandwagon, as my primary platform is Linux, I need good tooling here, but the Mono community is huge and it should lend itself even better to game development than OCaml (Maybe even first-class Unity support?).

Roc is a up and coming functional language, I do like the syntax, definitely want to play around with it at some point.

And SBCL, well… Look, I like Lisp, I wrote a few Emacs extensions and have a relatively good understanding of it, but when I wrote a Pong clone in that (yes I tried it), I was a little turned off, the sbcl REPL is a little cumbersome (no readline support, very verbose, drops me into nested “menus” on errors, and requires multiple EOFs to exit out of), on top of that the compiled binary is huge (~60 MiBs just for Pong with Raylib), a pass for now. But, if you, the reader, are in the market for an embedded extension language, please take a look at janet, a lovely embeddable lisp, really recommend this one, maybe skip Lua? 👀

@27justin github   codeberg   mail