Identify Side Effects And Refactor Fearlessly

When we refactor code how can we be confident that we don't break anything?

3 of the most important things that allow us to refactor fearlessly are:

  • Side effect free - or pure - expressions
  • Statically typed expressions
  • Tests

In this article we will solely focus on the aspect of side effects and strictly speaking on how to identify them. Being able to identify side effects in our programs clearly is the precondition for eliminating them.

Why avoid side effects?

Continue reading →

PureScript Case Study And Guide For Newcomers

Have you ever wanted to try out PureScript but were lacking a good way to get started?

If you

  • Have some prior functional programming knowledge - maybe you know Haskell,Elm,F#,or Scala,etc.
  • Want to solve a small task with PureScript
  • And want to get started quickly

This post is for you!

In this post we will walk through setting up and implementing a small exemplary PureScript application from scratch.

Continue reading →

Elm And The Algorithm Of Music

In this article I would like to present a minimal implementation of a music data type and everything that is needed to turn that into audible sound from an Elm application.

We will see how to transcribe an existing composition - an excerpt from Chick Corea's Children's Songs No. 6 - and listen to the result right here,embedded in this article.

From a music data type to performance

My colleague Jonas recently pointed out the presentation Making Algorithmic Music by Donya Quick to me. Donya Quick shows how she uses the Haskell library Euterpea to produce algorithmic music.

It got me really excited about the idea of porting this to Elm and to be able to use this in web applications.

In the following we will see the core data types and algorithms from Euterpea ported to Elm. To focus on the core concepts the implementation is stripped down to the minimum that is required to transcribe and perform an existing polyphonic piece of music (for a single instrument).

Continue reading →

Interactive Command Line Applications In Scala –Well Structured And Purely Functional

This post is about how to implement well structured,and purely functional command line applications in Scala using PureApp.

PureApp originated in an experiment while refactoring out some glue code of an interactive command line application. At the same time it was inspired by the Elm Architecture Pattern,and scalaz's SafeApp,as well as scalm.

To show the really cool things we can do with PureApp,we will implement a self-contained example application from scratch.

This application translates texts from and into different languages. And it provides basic user interactions via the command line.

The complete source code is compiled with tut. Every output (displayed as code comments) is generated by tut.
Continue reading →

How To Use Applicatives For Validation In Scala And Save Much Work

In this post we will see how applicatives can be used for validation in Scala. It is an elegant approach. Especially when compared to an object-oriented way.

Usually when we have operations that can fail,we have them return types like Option or Try. We sequence operations and once there is an error the computation is short circuited and the result is a None or a Failure.

Applicatives allow us to compose independent operations and evaluate each one. Even if an intermediate evaluation fails. This allows us to collect error messages instead of returning only the first error that occurred.

A classic example where this is useful is the validation of user input. We would like to return a list of all invalid inputs rather than aborting the evaluation after the first error.

Scala Cats provides a type that does exactly that. So let's dive into some code and see how it works.

Continue reading →

Parsers in Scala built upon existing abstractions

After some initial struggles,the chapter Functional Parsers from the great book Programming in Haskell by Graham Hutton,where a basic parser library is built from scratch,significantly helped me to finally understand the core ideas of parser combinators and how to apply them to other programming languages other than Haskell as well.

While I recently revisited the material and started to port the examples to Scala I wasn't able to define a proper monad instance for the type Parser[A].

The type Parser[A] alias was defined like this:

type Parser[A] = String =>Option[(A,String)] // defined type alias Parser 

To test the monad laws with discipline I had to provide an instance of Eq[Parser[A]]. Because Parser[A] is a function,equality could only be approximated by showing degrees of function equivalence,which is not a trivial task.

Also the implementation of tailRecM was challenging. (I couldn't figure it out.)

Using existing abstractions

Continue reading →

Strongly Typed Configuration Access With Code Generation

Most config libraries use a stringly typed approach.

Some handle runtime failures due to invalid configuration schemas by leveraging data types like Option or Result to represent missing values or errors. This allows us to handle these failures by either providing default values or by providing decent error messages.

This is a good strategy that we should definitely stick to.

However,the problem with default values is that we might not even notice if the configuration is broken. This could potentially fail in production. In any case an error e.g. due to a misspelled config property will be observable at runtime at the earliest.

Wouldn't it be a great user experience (for us developers) if the compiler told us if the configuration schema is invalid? Even better,imagine we could access the configuration data in a strongly typed way like any other data structure,and with autocompletion.

Moreover,what if we didn't have to write any glue code,not even when the configuration schema changes?

This can be done with the costs of an initial setup that won't take more than probably around 5 minutes.

Continue reading →

Error and state handling with monad transformers in Scala

In this post I will look at a practical example where the combined application (through monad transformers) of the state monad and the either monad can be very useful.

I won't go into much theory,but instead demonstrate the problem and then slowly build it up to resolve it.

You don't have to be completely familiar with all the concepts as the examples will be easy to follow. Here is a very brief overview:

Continue reading →

Use lambdas and combinators to improve your API

If your API overflows with Boolean parameters,this is usually a bad smell.

Consider the following function call for example:


When looking at this snippet of code it is not very clear what kind of effect the two Boolean parameters will have exactly. In fact,we would probably be without a clue.

We have to inspect the documentation or at least the parameter names of the function declaration to get a better idea. But still,this doesn't solve all of our problems.

The more Boolean parameters there are,the easier it will be for the caller to mix them up. We have to be very careful.

Moreover,functions with Boolean parameters must have conditional logic like if or case statements inside. With a growing number of conditional statements,the number of possible execution paths will grow exponentially. It will become more difficult to reason about the implementation code.

Can we do better?

Sure we can. Lambdas and combinators come to the rescue and I'm going to show this with a simple example,a refactoring of the function from above.

This post is based on a great article by John A De Goes,Destroy All Ifs — A Perspective from Functional Programming.

I'm going to take John's ideas that he backed up with PureScript examples and present how the same thing can be elegantly achieved in Scala.

Continue reading →

Modelling API Responses With sbt-json –Print Current Bitcoin Price

I'm currently working on an sbt plugin that generates Scala case classes at compile time to model JSON API responses for easy deserialization especially with the Scala play-json library.

The plugin makes it possible to access JSON documents in a statically typed way including auto-completion. It takes a sample JSON document as input (either from a file or a URL) and generates Scala types that can be used to read data with the same structure.

Let's look at a basic example,an app that prints the current Bitcoin price to the console.

Continue reading →

'|Droid+Sans+Mono|Open+Sans:400,600,700';.elm-music-play-button,.elm-music-stop-button{margin:2px;}span.n{color:#96C71D;}table.pre,pre.fssnip,pre{line-height:13pt;border:1px solid #d8d8d8;border-collapse:separate;white-space:pre;font:9pt'Droid Sans Mono',consolas,monospace;width:90%;margin:10px 20px 20px;background-color:#212d30;padding:10px;border-radius:5px;color:#d1d1d1;max-width:none;}@media screen{@font-face{font-family:'FontAwesome';src:url(/wp-content/themes/editor/inc/fontawesome/fontawesome-webfont.eot);src:url(/wp-content/themes/editor/inc/fontawesome/fontawesome-webfont.eot) format('embedded-opentype'),url(/wp-content/themes/editor/inc/fontawesome/fontawesome-webfont.woff) format('woff'),url(/wp-content/themes/editor/inc/fontawesome/fontawesome-webfont.ttf) format('truetype'),url(/wp-content/themes/editor/inc/fontawesome/fontawesome-webfont.svg) format('svg');font-weight:normal;font-style:normal;}.fa{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);}100%{-moz-transform:rotate(359deg);}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);}100%{-webkit-transform:rotate(359deg);}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);}100%{-o-transform:rotate(359deg);}}@keyframes spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg);}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg);}}.fa-times:before{content: "\f00d";}.fa-folder:before{content: "\f07b";}.fa-folder-open:before{content: "\f07c";}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content: "\f0c9";}.fa-arrow-circle-o-left:before{content: "\f190";}#simple-social-icons-2 ul li a,#simple-social-icons-2 ul li a:hover,#simple-social-icons-2 ul li a:focus{background-color:#999 !important;border-radius:3px;color:#fff !important;border:0px #fff solid !important;font-size:18px;padding:9px;}}

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 →

Template Method Pattern. Can we do better?

Often we encounter algorithms with a certain structure that consist of individual steps that may vary for specific implementations.

To keep things clean and in order to reduce duplicate code we should refactor common parts out.

The object-oriented solution to this is the Template Method design pattern.

But there might be an alternative, better solution to this that uses higher-order functions.
Continue reading →

Parsing Roman Numerals in C# and Haskell

This is a follow-up from my last post Functional Monadic Parsers ported to C# where I showed the implementation of basic parsers from the book Programming in Haskell by Graham Hutton in C#.

When these primitives are used to compose a parser for Roman Numerals the result yet again demonstrates the amazing capabilities and elegance of functional programming. The problem of parsing Roman Numerals is not a very difficult one. But still, I find the simplicity of constructing a solution by combining primitive parsers fascinating.

Here is the implementation. It is super easy, I was able to write this in less than 15 minutes without tests first, worked the first time.
Continue reading →

Functional Monadic Parsers ported to C#

While taking the MOOC Introduction to Functional Programming by Erik Meijer on edX the current lecture greatly increased my interest in functional parsers. Functional parsers are about the essence of (functional) programming because they are about the concept of composition which is one of the core concepts of programming whatsoever.

The content of the lecture is closely related to the chapter 8 Functional Parsers of the book Programming in Haskell by Graham Hutton. It starts out with the definition of a type for a parser and a few very basic parsers.

I'm totally amazed by the simplicity, the elegance and the compositional aspect of these examples. I find it impressive how primitive but yet powerful these simple parsers are because they can easily be combined to form more complex and very capable parsers.

As an exercise, out of curiosity, and because of old habits I implemented the examples from the book in C#.

At the end of this post there will be an ultimate uber-cool parser example of a parser for arithmetic expressions.

The complete code from this post can be found here on GitHub.

Here is what I got:

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=""></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.

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 →

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

Viewmodel property to observable stream

When implementing a user interface in WPF/MVVM applications we frequently encounter situations where we want to be able to react on all changes made to a particular property.

One way to handle this is to create an observable sequence of values with Reactive Extensions (Rx). This is especially valuable if we have other event streams that interact with the property changed events.

There are several libraries around that can help with this like e.g. ReactiveUI or ReactiveProperty.

But if we want a lightweight, generic, reusable, and typesafe solution, we can consider just using the following extension method, which can be called on any instance that implements INotifyPropertyChanged. It retrieves the property name from the expression that is passed in, converts all PropertyChanged events into an observable sequence, and then finds the value of the right property using reflection.

Continue reading →