How F# can help with the pitfalls of C# enumerations

I don’t get it. Even in a statically typed language like C# you can change the domain model and your application will still compile as if nothing happened. In this post we will address this and see how F# can help with such pitfalls of C# enumerations.

What’s the problem?

The problem with enumerations is simply that when we add new cases especially in a large code base, it can be really hard to find and update all dependent source code which might lead to errors at runtime.

The compiler will not help to find all the places that have to be updated. A text-based search isn’t reliable.

Here is how things can go wrong.

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 =
            Options(
                title = "Status", 
                orientation = "horizontal")

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

            chart.InlineHtml

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">
  google.charts.setOnLoadCallback(drawChart);
  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);
        }
</script>
<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']});
  google.charts.setOnLoadCallback(drawChart);
</script>

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:

<div>
    @Html.Raw(@Model.Chart)
</div>

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

Here is the source code from this post.

Functional error handling – parsing command line arguments in C#

This is the third part of the series Functional error handling in F# and C#. In this post we will see how the command line argument parser with functional error handling, that was shown here using F#, can be implemented in C#.

Continue reading →

Functional error handling – parsing command line arguments in F#

In this post, which is the second part of the series Functional error handling in F# and C#, we will examine an application for parsing command line arguments with error handling.

The functional approach uses Applicative Functors. Applicative Functors and the basics of functional error handling, only with immutable objects and without the use of exceptions, are explained int the first post of this series: Error handling with Applicative Functors in F# and C#.

A complete solution with all the code samples from this series can be found here.

As a starting point I took this F# console application template and reimplemented it with railway oriented error handling in F# and C#. The original version writes error messages directly to the console, which is totally ok in many situations. However, the railway oriented approach offers a bit more flexibility and safety because it will let the caller decide on how to handle the failure cases.

Continue reading →

Error handling with Applicative Functors in F# and C#

In an object-oriented context a typical way to do error handling is to use the Notification Pattern described by Martin Fowler.

In functional programming (FP) the approach to error handling is very different. Error handling has to be done without mutating state and without the use of exceptions. The concept that is capable of this, and that is commonly used in FP is called “Applicative Functor”.

In this post, which is the first part of the series Functional error handling in F# and C#, we will cover all the basics that are needed to do functional error handling in F# and C#, and to understand Applicative Functors.

The F# and C# code samples from this post can be found here.

In the second part of the series we will look at a sample application for parsing command line arguments with error handling in F#.

Anyway, before we jump right into it, we will need some introduction.

Continue reading →

Convert an Action into an F# function returning unit

Let’s say we want to pass an Action<T> as an argument from C# code to a F# function that might look something like this:

module MyModule = 

    let doSomething log =
        do log "doing something"
        "result"

It took me an almost unreasonable amount of time today to figure out how to do this. So that’s why I’d like to share this.

First since F# doesn’t know actions the action has to be converted to a Func<T, Unit>. The tricky part is to create an instance of Unit because Unit neither has a public constructor nor any factory methods. After referencing Microsoft.FSharp.Core it can be done with reflection:

var unit = (Unit)Activator.CreateInstance(typeof(Unit), true)

Now we convert the Action<T> to a Func<T, Unit>:

public static Func<T, Unit> ToFunc<T>(this Action<T> action)
{
    return x => { action(x); return (Unit)Activator.CreateInstance(typeof(Unit), true); };
}

Next the new function can be converted to an FSharpFunc<T, Unit>:

public static FSharpFunc<T, Unit> ToFSharpFunc<T>(this Action<T> action)
{
    return FSharpFunc<T, Unit>.FromConverter(new Converter<T, Unit>(action.ToFunc()));
}

Here is the complete code that does everything:

using System;
using Microsoft.FSharp.Core;

namespace FSharpConverter
{
    public static class ToFSharpFuncConverterExtensions
    {
        private static readonly Unit Unit = (Unit)Activator.CreateInstance(typeof(Unit), true);

        public static Func<T, Unit> ToFunc<T>(this Action<T> action)
        {
            return x => { action(x); return Unit; };
        }

        public static FSharpFunc<T, Unit> ToFSharpFunc<T>(this Action<T> action)
        {
            return FSharpFunc<T, Unit>.FromConverter(new Converter<T, Unit>(action.ToFunc()));
        }
    }
}

Now we can use this in our C# code:

Action<string> logger = Console.WriteLine;
var fsharpLogger = logger.ToFSharpFunc();
MyModule.doSomething(fsharpLogger);

Example

Here is an example where I used this: GUI for a functional Tic-Tac-Toe implementation

Update

In the meantime I found out that there is actually a very rich library that supports this and a lot more C# – F# interoperability: FSharpx.Extras