# Implementing the MessagePack specification in Purescript

In my post, The One Editor Who Currently Rules Them All I laid out my first steps for taking down Abner Lee’s Typora. (which you should totally use because it’s great)

- Use Purescript
- Build on top of neovim
- (2) requires a Purescript implementation of the MessagePack binary serialization format

## What is an implementation of MessagePack

At its essence, this project is about providing two functions:

`encode :: a -> MessagePack a`

`decode :: MessagePack a -> Maybe a`

For those of you who haven’t already drinken the Function Programming Koolaid I will explain what `a`

and `Maybe a`

are. `a`

is a placeholder for any type. This implies that `encode`

takes a value of some type `a`

and provides me the MessagePack version of that value and `decode`

takes a MessagePack-ified value of type `a`

and returns a `Maybe a`

. The Maybe is important because if the input is malformed, then the decoding will fail and there will not actually be a value of type `a`

to retrieve. We can rewrite the type signature to make this clearer:

```
decode :: MessagePack a -> (Just a | Nothing)
```

/fp-koolaid

## Writing an implementation of MessagePack

One neat thing about Purescript is that it compiles down to JavaScript. This affords a high degree of interoperability between JavaScript libraries and Purescript code. It turns out that there exists a JavaScript implementation of Message Pack, which means that our job got a whole lot easier.

This means that we can leverage the Foreign Function Interface (FFI) to create a Purescript interface on top of the JavaScript implementation. I’m not suggesting that we completely cop out and use a non-type safe pig with some Purescript lipstick on it, but we could define our interface and testing infrastructure around a correct implementation. Then we can gradually introduce our own native Purescript solution and everyone wins.

This yields the following plan:

- Create a Purescript interface and types for Message Pack
- Leverage the FFI to use the existing JavaScript library to implement the interface
- Write tests in Purescript that verify the implementation
- Gradually replace usage of the FFI’d JavaScript library with a pure Purescript solution

Let’s see how this goes!