Monads in F#

When I first tried to learn what monads were, I probably made the mistake of going to wikipedia, which only made things worse. It was not until I began to play with parser combinators that I started to grasp the concept.

What are monads?

You probably heard the word monad if you have dealt with functional programming. However, to me the word is rather obscure, and might sound a little daunting to people starting in functional programming. This is one of the reasons why the creators of F# decided to avoid this term and use the word workflow or computation expression instead.

Ok… but what are they?

Basically, monads are just a typeclass and two fundamental operations associated. Think of a generic interface with two abstract methods. These operations have the following syntax:

Return: 'a -> M<'a>
Bind: M<'a> -> ('a -> M<'b>) -> M<'b>
Read more

Introduction to Parser Combinators

So I have been playing with parser combinators for quite a while now and they felt so interesting that I wanted to write about them.

What is a parser?

Basically a parser is a function which accepts some sort of character input such a string or a character stream and returns some structure as output that contains the parsed result. It is as simple as it sounds, no intricacies here.

Parsers are used everywhere in software in order to interpret character sequences into complex structures. Some simple example are JSON and XML parsers, which take some string as argument and return the corresponding data structure.

Using F#, we can define a simple parser type as follows:

type ParserResult<'a> =
    | Success of 'a * list<char>
    | Failure

type Parser<'a> = list<char> -> ParserResult<'a>

This means that a Parser will receive a list<char> and will return a ParserResult<'a> which can be either a Failure if nothing could be parsed or a Success otherwise and return both the parsed element and the rest of the list.

Read more