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 →

Series: Functional error handling in F# and C#

Some time ago when I started learning functional programming I also started to follow functional programmers on twitter. Some day someone stated that error handling should be done with Applicative Functors.

Off course the Fowler way is a very typical, commonly used and approved approach. So what makes it so much better to use Applicative Functors instead? And what are they anyway?

This series of posts will answer these questions. It is the kind of article I was looking for back then but could not find. It is a compilation of all the pieces and resources that I found researching the topic.

In the first part we will cover all the basics that are needed to do error handling in a functional style, and to understand what is going on behind the scenes. We will see how error handling can be done only with immutable objects and without using exceptions.

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

Content of this series:

  1. Error handling with Applicative Functors in F# and C#
    Basics of functional error handling

  2. Functional error handling – parsing command line arguments in F#
    Functional error handling in practice (F#)

  3. Functional error handling – parsing command line arguments in C#
    Functional error handling in practice (C#)

  4. Functional vs. imperative error handling
    A comparison of the functional vs. the imperative approach to error handling

Function composition in C#

Function composition is about the essence of programming. Complex problems can be solved by decomposing them into many smaller problems that each can be worked out easily. Finally those small pieces have to be put together to form the overall solution. One way of combining these small pieces is function composition.

Also function composition is a great tool that makes the code more compact and reduces noise. Because of the concise syntax there are fewer possibilities to make mistakes like mixing up parameters e.g.

In this post I will show how function composition can be implemented in C# and how it is related to currying and partial application. Also I will discuss the pros and cons of function composition in C# and point out an alternative. All C# source code from this post can be downloaded here.

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