Why is SelectMany so weird?

Part III of the series Fun with Functional C#.
March 17, 2016

This episode, we’ll be looking at why SelectMany will look so strange to Haskell users, why that’s linked to some implementation-level issues with C#, and the extremely cool way that the C# team got around those issues.

A quick recap: LINQ query syntax is actually just Haskell do-notation, specialized for the list monad.

We can see this by looking at the signature for SelectMany:

IEnumerable<B> SelectMany<A, B>(
  this IEnumerable<A> source,
  Func<A, IEnumerable<B>> selector

It’s a less polymorphic Haskell bind:

bind :: Monad m => m a -> (a -> m b) -> m b

When I first saw this, I immediately attempted to write my own monad instance in C#, and had a Bad Time. But figuring out why it wasn’t so easy was probably more interesting than writing the monad instances in the first place!


The Reader Monad

Part II of the series Fun with Functional C#.
March 16, 2016

In this installment of Fun with Functional C#, we’re going to be implementing the reader monad, and attempting to figure out if it’s actually useful. The reader monad was the first monad I implemented when I found out that SelectMany was bind. I thought it would be a good way to get rid of runtime dependency injection errors, but it turned out not to be the panacea I’d hoped for.


The first thing I did was implement SelectMany, but it had some quirks that I’ll discuss in the next installment of this series. For now, let’s just look at the implementation:

public class Reader<E, A>
    private Func<E, A> f;
    public Reader(Func<E, A> func) 
        f = func;

    public A RunReader(E env) 
        return f(env);

This is basically equivalent to

newtype Reader e a = Reader { runReader :: (e -> a) }

Functional C#

Part I of the series Fun with Functional C#.
March 15, 2016

With the introduction of LINQ in C#3, Erik Meijer and co. rebranded monads and presented them to a huge audience, and I think the way they did it was a brilliant piece of programming language UX design.

Apparently, before Erik Meijer joined the team working on LINQ, their goal was just to reduce the impedance mismatch between SQL databases and C#. So the solution they came up with was to let developers query SQL databases by writing SQL queries directly within C#- basically a language-level ORM.

I guess someone must have pointed out, wait a minute, there’s also the same impedance mismatch when you’re interacting with XML data- why are we limiting ourselves to relational databases?

And then Erik Meijer came along1 and said, query comprehension can be represented as a monad, so we can do all these things, and make it work for in-memory objects too, and reactive streams, and any queryable we can think of!

Now Pandora’s Monad2 is open, the M-word is floating around the hallways and people are getting into heated discussions about the Yoneda Lemma and the co-Yoneda lemma. Your coworkers are saying, look at Haskell, these problems have been solved in a general way for years!

It must have been tempting to just blindly retrofit functional concepts into C# and tell developers to just fmap and fold and bind to their heart’s content. But they didn’t, because immediately grasping the utility of these concepts is almost impossible at first glance, so they stuck a particular abstraction level and stuck with it. I guess a part of it could have been that C#’s type system can’t actually represent monads, but to me it looked like a concious design decision to solve the problem at an appropriate level of abstraction.


Prerendering MathJax

September 14, 2015

I use MathJax on this blog. It’s a great tool, but it’s really slow, and worse, it’s slow in a way that draws attention to itself. A page with even a bit of MathJax will go through these stages:

  1. Unrendered MathJax markup
  2. Initial render with incorrect font
  3. Render with correct font, but with incorrect spacing and alignment
  4. Render correctly

The entire process can take a few seconds, and it’s rather jarring to watch text reflow at each stage as MathJax renders.

Khan Academy has noticed this problem, so it’s developed an alternative called KaTeX, which can render at many times the speed of MathJax. Unfortunately, it only implements a small subset of MathJax’s functionality, and I wanted to draw commutative diagrams, which weren’t supported. Even quite basic things like \begin{split} aren’t yet supported, so I’m stuck with MathJax for the time being.


Free monads in 7 easy steps

Part I of the series Free monads.
September 13, 2015

In the next part of this series, we’ll discuss free monads from a category theory perspective. This first installment will be decidedly more practical, focusing on how you actually use free monads in Haskell, and what advantages they bring. This means I’ll gloss over a lot of the mechanics of how free monads actually work, and make this more of a “get it done” kind of post.

The finest imperative language?

Simon Peyton-Jones famously said that Haskell was the world’s finest imperative programming language. When I started writing Haskell, however, I literally tacked -> IO () onto the end of all my functions and went to town writing imperative code.

Of course, not all the functions I wrote returned an IO (), but because that was the only tool that I had to interact with the outside world, a great deal of my code- far more than necessary- simply lived inside the IO monad.

Here’s a pretty representative example, from a program I wrote that implemented anonymized network chat1:

keyExchangeHandler :: Either String PeerData -> MVar ServerState -> IpAddress -> Int -> Handle -> IO ()
keyExchangeHandler p state ip portNumber handle = case p of
  Right peerData -> do
    s <- takeMVar state
    let peer = Participant (publicKey peerData) (nonce peerData) ip portNumber
    let newPs = peer:(peers s)
    if length newPs == groupSize s
       then forkIO $ sendPeerList state
       else forkIO $ putStrLn "Waiting for peers"
    putMVar state s{ peers = newPs }
  Left e -> putStrLn $ "Could not parse public key: " ++ e

The semantics of the application logic are completely mixed up with implementation-level details, and having all these functions just return IO () meant that I wasn’t exploiting a lot of the safety that the type system could provide. It was essentially Haskell-flavoured Java2! You can take a look at what the code looked like back then here.

Alright, so we don’t want a bunch of opaque IO () functions, but wouldn’t refactoring to use the free monad be really painful?

Not at all! Here’s how you use free monads, in just seven easy steps!


Previous Next