Purity in an impure language with the free monad – by example of a Tic-Tac-Toe backend with CQRS and event sourcing

This post is part of the F# Advent Calendar in English 2016. Please also checkout the other posts or the F# Advent Calendar 2016 eBook.

Pure code intermingled with impure code.

This is not a very good separation of concerns and has many other disadvantages.

Here is an example of how many programs look like:


In Haskell e.g. this would not be possible. But how should we deal with this in an impure programming language that does not enforce side effects to be made explicit, like F# e.g.?

There are a few approaches that will be presented in this post, one of which is the free monad pattern.

We will also examine a proof of concept implementation of a Tic-Tac-Toe backend following the command query responsibility segregation pattern (CQRS) together with event sourcing (ES).

See how you can implement a program in F# that is entirely pure and free from any effects and side effects!
Continue reading →

How to parse a Git log with FParsec

In this post we will see how to parse a Git log using F# and FParsec.

FParsec is a parser combinator library for F#. The library provides many simple parser functions that can be combined to create quite complex and powerful parsers.

For an introduction on how this works please refer to Functional Monadic Parsers ported to C# which explains some basic concepts and shows how a parser combinator library is built from scratch. Another good starting point is the FParsec tutorial or this post by Mathias Brandewinder.

In this post, however, we will focus on the usage rather than on how it works.

Complete Gist for this post.

Continue reading →

SameGame with F# and Fable: Functional programming meets JavaScript

Fable is a compiler for F# to JavaScript.

It brings all the good parts of functional-first programming in F# to JavaScript development.

Even without a lot of knowledge of Node.js and the JavaScript ecosystem, it is fairly easy to get started with and use functional-first programming for client-side browser applications. Fable can also be used for client-server, Node, mobile or desktop applications.

After reading the very nice introductory tutorial Getting started with Fable and Webpack I was ready to make an implementation of SameGame.

It is integrated in this post and you can play it right here in the browser.

This sample was also published on Fable’s official sample site where you can find more information on the implementation details.

Continue reading →

Functional error handling in F# by example

Exceptions are bad.

Not only do we have to remember to catch them everywhere, they also provide a second implicit exit strategy for functions, similar to the goto statement.

However, there is an alternative more explicit approach.

In this post we will go through an example of how to implement decent functional error handling in F# without using NULL or exceptions.

We will do this by extending the application from the last post and make it even more reliable and robust.

Continue reading →

Writing efficient and reliable code with F# Type Providers

F# type providers are just awesome because they help to write very efficient and reliable code.

In this post I will show this by implementing a simple, but real-world-like scenario with some F# type providers.

Type providers provide the types, properties and methods to get access to external data sources of various kinds without having to write a lot of boiler-plate code. This makes coding very efficient.

Additionally they offer static types that represent external data and that the compiler will check at compile time. This makes coding very reliable.

So let’s look at the scenario that we are going to implement…
Continue reading →

Domain Design, data- or function-centric?

There are two great articles by Scott Wlaschin on how functional programming can be used for the domain design of real-world applications by implementing a Tic-Tac-Toe game. He demonstrates how business rules can be modeled with types, how data hiding, encapsulation, logging and capability-based security can be achieved with functional programming and more.

What I found remarkable is that in the second article he completely re-engineered the first design. Even though to me the original implementation appeared to be very appealing.

I liked that the data-centric domain model was concise, totally clear and very close to the natural notion of the game. Eventually it couldn’t meet high security standards since there were ways for malicious users of the API to manipulate the data.

The second function-centric implementation introduced the concept of capability-based security. The design smells of the previous version could be resolved. But I argue that the API of the second version is not as intuitive as the first one anymore. Technically it is also quite simple. However, the recursive structure doesn’t come totally natural to me. Also an indicator that the second version is more complex is that logging becomes trickier.
Continue reading →

Refactoring to FParsec

I have been playing around with FParsec a little bit lately, inspired by the chapter 8 “Functional Parsers” of the book Programming in Haskell by Graham Hutton. FParsec is an F# parser combinator library for building quite powerful parsers by combining primitive parsers and functions provided by the FParsec library.

If you haven’t been exposed to the concept of functional monadic parsers then this can be a very different experience. I am still totally fascinated by the power and the simplicity of this concept. Here is a brief introduction in C#.

As an exercise and to learn the usage of FParsec I have been looking for code that could be refactored to FParsec.

Continue reading →

XPlot ‘hello world’ – Using Google Charts in Web Applications

In this post I will describe the very basics, in other words the ‘hello world example’, of how to create cool looking Google Charts using XPlot and integrate them into Web Applications.

The F# library XPlot is part of the FsLab data science package, which you can do very neat things with. But it is also possible to reference an XPlot stand-alone package to just use the Google Charts library.

What is XPlot?

XPlot is a cross-platform data visualization package for the F# programming language powered by popular JavaScript charting libraries Google Charts and Plotly. The library provides a complete mapping for the configuration options of the underlying libraries and so you get a nice F# interface that gives you access to the full power of Google Charts and Plotly. The XPlot library can be used interactively from F# Interactive, but charts can equally easy be embedded in F# applications and in HTML reports. —From XPlot Home Page

Creating the chart

There are only a few easy steps necessary to generate the HTML for let’s say a simple bar chart.

First we need an F# library project that references the XPlot.GoogleCharts package via NuGet.

Here is a function that will use XPlot to create the HTML and JavaScript code for a simple bar chart:

namespace Charts

module BarCharts =
    open XPlot.GoogleCharts

    let statusCount () =

        let series = [("Open",23); ("In Progress",5); ("Resolved", 58); ("Closed",5)]

        let options =
                title = "Status", 
                orientation = "horizontal")

        if series |> Seq.isEmpty then "no data" else
            let chart = 
                |> Chart.Bar
                |> Chart.WithOptions options
                |> Chart.WithLabels ["Count"]


The result can be used in any web application if the Google Charts libraries are loaded.

series can be any list of tuples of type (string * int). Off course, in a real project this list would be either passed to the function as an argument, or the function would have a data access dependency injected.

Here is the output of the statusCount() function:

<script type="text/javascript">
  function drawChart() {
    var data = new google.visualization.DataTable({"cols": [{"type": "string" ,"id": "Column 1" ,"label": "Column 1" }, {"type": "number" ,"id": "Count" ,"label": "Count" }], "rows" : [{"c" : [{"v": "Open"}, {"v": 23}]}, {"c" : [{"v": "In Progress"}, {"v": 5}]}, {"c" : [{"v": "Resolved"}, {"v": 58}]}, {"c" : [{"v": "Closed"}, {"v": 5}]}]});

    var options = {"legend":{"position":"right"},"orientation":"horizontal","title":"Status"} 

    var chart = new google.visualization.BarChart(document.getElementById('9af3e989-c37b-4257-b71f-5053b52f3b48'));
    chart.draw(data, options);
<div id="9af3e989-c37b-4257-b71f-5053b52f3b48" style="width: 900px; height: 500px;"></div>

Displaying the chart in an ASP.NET MVC application

Now, as an example, we will see how to integrate this into an ASP.NET MVC application.

Loading the Google Charts Library

Load the Google Charts library by adding the following lines to the <head> section of the page e.g. in _Layout.cshtml. (Also see
Load the Libraries

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  google.charts.load('current', {packages: ['corechart']});

Initializing the View Model

Add a reference to the F# project that was created earlier and build the F# project.

Next add a reference to FSharp.Core.

Then initialize a View Model with the chart and pass it to the View:

public ActionResult Index()
    var vm = new BarChartVm
        Chart = Charts.BarCharts.statusCount()

    return View(vm);

Add the following code to the page at the position where the chart should be displayed:


When running the application, the chart should be displayed like this:

Here is the source code from this post.

SQL Type Providers and Continuous Integration with FAKE

If you want to access a relational database from an F# (or C#) application, SQL F# type providers are commonly used. SQL type providers will provide all the types, properties and methods needed to access and interact with the tables of a SQL database, without having to write any extra boilerplate code. Everything is type checked and if the actual database schema gets out of synch with the database related code, compilation will fail. This is very valuable because it gives you high confidence in the application’s data access code.

So at compile time the database has to be up to date and accessible. But how does this work in a continuous integration environment? Off course an option is to have the connection string of the type provider point to a development database on the network. Another solution would be to manually create or update a database on the build server before the build. But I don’t really like this because I think the build server should be independent and self-sufficient. A solution to this scenario, that worked for me, is to deploy the database during the build process using Visual Studio database projects and FAKE – F# Make.

There might be other and maybe better solutions that I haven’t come up with. I’d be curious to find out. Actually this might be one. The approach that I used, however, works out nicely, so I will give a quick walkthrough on how to set things up.

Continue reading →