Category Archives: F#

How to prevent F# union case names leaking into parent scope

Suppose you are writing some F# code to model the workings of a coffee shop. You might start by defining a small choice of snacks:

type Cost = int

type Muffin =
| RaspberryAndWhiteChocolate of Cost
| Blueberry of Cost
                          
[<EntryPoint>]
let main argv = 
    // No need for "Muffin." qualifier on Blueberry
    let muffin = Blueberry 250 

    printfn "%A" muffin
    0

This compiles and runs just fine – notice that there’s no requirement to prefix the union case “Blueberry” with the type name “Muffin”. All is well.

However, suppose you then proceed to define some more types for coffee:

              
type Milk =
| Skimmed
| Whole
| SemiSkimmed

type Modifier =
| Milk of Milk
| Cream
| None   // <--- Oops, clashes with FSharpOption.None
             
type Coffee =
| Filter of Modifier
| Cappuccino
| Latte

[<EntryPoint>]
let main argv = 

    let muffin = Blueberry 250

    let coffee = Filter( None )

    printfn "%A %A" muffin coffee
    0

This still compiles and runs – but there’s a lurking problem. As soon as you add the use of optional values, the program fails to compile. For example, you might offer free coffee as a promotion, and model the cost as optional:

    let coffee = Filter( None )
    let cost : int option = None

compileerror
The problem is that None is now used as both a union case in Modifier and a union case in FSharpOption.

Whilst you could choose to workaround this by changing the “None” union case in Modifier to “Nothing”, you may not have that flexibility. Instead, you can use the RequireQualifiedAccess attribute on the Modifier type to stop union case names leaking into the surrounding scope:

[<RequireQualifiedAccess>]
type Modifier =
| Milk of Milk
| Cream
| None 

[<EntryPoint>]
let main argv = 
    let muffin = Blueberry 250 // still no qualifier required
    let coffee = Filter( Modifier.None ) // now requires qualifier
    let cost : double option = None // ok, uses FSharpOption.None

    printfn "%A %A %A" muffin coffee cost
    0

Leave a comment

Filed under F#

How to extend F# discriminated unions for use from C#

Some time ago, I wrote about calling C# byref methods from F#. This time, I wanted to do things in reverse – the motivation being to provide a neat way of working with F# discriminated unions from C#.

Now, some support comes for free when you define a discriminated union in F#. For example, given this union type:

type Vehicle
| Car of int // number of doors
| Lorry of double // weight in tonnes

then from C#, you could query the union case in turn like this:

if (vehicle.IsCar)
{
    var doors = ((Vehicle.Car)vehicle).Item;
    driveCar( doors );
}
else if (vehicle.IsLorry)
{
    var weight = ((Vehicle.Lorry)vehicle).Item;
    driveLorry( weight );
}

However, although the provided “Is” methods are neat, the cast and the requirement to call “.Item” are rather ugly. What you really want is the ability to get the value of the union case without casting. That’s achievable if you add these methods to the original union definition by hand:

using System.Runtime.InteropServices // for [<Out>]
type Vehicle
| Car of int // number of doors
| Lorry of double // weight in tonnes
with
    member this.TryGetCar( [<Out>] result : int byref ) =
        match this with
        | Car doors ->
            result <- doors
            true
        | _ -> false
    member this.TryGetLorry( [<Out>] result : double byref ) =
        match this with
        | Lorry weight ->
            result <- weight
            true
        | _ -> false

Now the experience is much better from C#:

int doors;
double weight;
if ( vehicle.TryGetCar( out doors ) )
{
    driveCar( doors );
}
else if ( vehicle.TryGetLorry( out weight ) )
{
    driveLorry( weight );
}

and the new methods are usable from F# as well, although you’d probably prefer to use match:

// Use TryGet approach - returns bool, int
let isCar, doors = vehicle.TryGetCar()

// Use match approach - more natural for F#
match vehicle with
| Car doors -> driveCar(doors)
| Lorry weight -> driveLorry(weight)

Leave a comment

Filed under F#, Programming

How to write Extension Methods in F# and Swift

I’ve used extension methods for a while in F# as a neat way of adding utility methods to system types. For example, suppose you have a set and want to add some elements to it? You might write something like this:

  let collection = ... // initial set defined elsewhere
  let collection = // add extra elements into collection
    [| 1; 2; 3 |] |> Array.fold (fun (acc : Set<'T>) item -> acc.Add item) collection

You might find yourself writing this snippet frequently and for different container types. Instead of defining the operation every time, it’s better to write an extension method:

namespace MusingStudio.Extensions
module Set =
  let AddMulti (items : seq<'T>) (collection : Set<'T>) =
    items |> Seq.fold (fun (acc : Set<'T>) item -> acc.Add item) collection

Then, by bringing the extensions into scope, we can call AddMulti as if it were part of the system Set interface:

open MusingStudio.Extensions

[<EntryPoint>]
let main argv = 
    let initial = [| 1; 2; 3 |] |> Set.ofArray
    let updated = initial |> Set.AddMulti [| 4; 5; 6 |]
    printfn "%A" updated
    0 // return an integer exit code

I was looking for a way to get the current time/date in Swift, and found some code on Stack Overflow that uses Extension Methods to do it. I’ve added a couple more methods to get the seconds and day-of-month:

import Foundation

// From: http://stackoverflow.com/questions/24070450/how-to-get-the-current-time-and-hour-as-datetime
extension NSDate
{
    func hours() -> Int
    {
        //Get Hours
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Hour, fromDate: self)
        let hours = components.hour
        
        //Return Hour
        return hours
    }
    
    func minutes() -> Int
    {
        //Get Minutes
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Minute, fromDate: self)
        let minutes = components.minute
        
        //Return Minute
        return minutes
    }
    
    func seconds() -> Int
    {
        // Get Seconds
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Second, fromDate: self)
        let seconds = components.second
        
        return seconds
    }
    
    func day() -> Int
    {
        // Get Day
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.Day, fromDate: self)
        let day = components.day
        
        return day
    }
}

This simplifies the interface to NSDate:

  // Get the time properties
  let currentDate = NSDate()
  let minutes = currentDate.minutes()
  let hours = currentDate.hours()
  let seconds = currentDate.seconds()
  let dayOfMonth = currentDate.day()

2 Comments

Filed under F#, Programming, Swift

F# Meetup – Microservices Chaos Testing

Meetup - Microservice Chaos TestingThis was the first event I’ve attended by the F#unctional Londoners group and the venue at Skillsmatter.com was excellent.

Some of the biggest growing pains we’ve experienced with our microservice architecture at Jet is in preparing for system outages.

In this talk, Rachel will discuss Jet.com’s chaos testing methods and code in depth, as well as lay out a path to implementation that everyone can use.

I haven’t used chaos testing in my own work, but in the world of distributed services, it makes sense to test the robustness of the system to failures on individual nodes. Rachel’s story was quite compelling, even if her own developers aren’t all convinced of the attractions of chaos testing on the production system just yet!

Leave a comment

Filed under F#, Meetup, Programming, Technology

How to conditionally compile against different .NET framework versions in F#

I recently needed to supply two variations of an algorithm in an F# source file – one for .NET 3.5 consumers and another for .NET 4.0 consumers (the later framework version allows parallel execution using the FSharp.Collections.ParallelSeq). One way is to tell msbuild to reference the library, conditional on the version of the .NET framework – and also, define a constant which can be used within the source code to choose the algorithm.

In msbuild, define a constant according to the framework

<PropertyGroup Condition=" '$Framework' == 'NET35' ">
  <DefineConstants>NET35</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$Framework' == 'NET40' ">
  <DefineConstants>NET40</DefineConstants>
</PropertyGroup>

In msbuild, reference library if .NET 4.0

<ItemGroup Condition=" '$Framework' == 'NET40' ">
  <Reference Include="FSharp.Collections.ParallelSeq"/>
</ItemGroup>

Specify conditional compilation directives in the source code

let doMapping = ... // some transformation
#if NET35
    items |> Seq.map doMapping
#else
    items |> FSharp.Collections.ParallelSeq.PSeq.map doMapping

Leave a comment

Filed under F#, Programming

How to write generic, duck-typing code in F#

When writing generic code in C++, it’s easy to imply constraints in the generic type when developing a template. For example:

template<class T> 
class Announcer{
public:
	static void announce( const T& t )
	{
		std::cout << "And now from " <<  t.country << ", we have: ";
		bool first = true;
		for ( auto person : t.people )
		{
			std::cout << person;
			if (!first) std::cout << "\n";
			first = false;
		}
	}
};

Here, we’re assuming that T has two properties, ‘country’ and ‘people’, with the latter being enumerable (i.e. supports begin/end methods and iterators). This is one of the attractions of C++ for generic code – although, in the future, concepts will enable you to document the constraints in order to make it easier for developers to use your library, and for the compiler to give clearer errors.

What about something similar in F#? I found Tomas Petricek’s post from StackOverflow very useful.

type IHasCountryProperty =
    abstract Country : string

type Announcer<'T when 'T :> IHasCountryProperty>( item : 'T) =
    member this.Announce() =
        printfn "And now the party from %s" item.Country

let inline countrifiedItem<'T when 'T : (member Country : string)> (item : 'T) =
    {
        new IHasCountryProperty with
            member this.Country = (^T : (member Country : string) item)
    }

type London() =
    member this.Country = "England"

// Use it
let city = London()
Announcer( countrifiedItem city ).Announce()

The Announcer class uses a member constraint with statically resolved type parameters which bind to the Country property. Then, the inline static function ‘countrifiedItem’ uses static member constraints to capture the existing Country property on any other type, even if like ‘London’ it doesn’t support the IHasCountryProperty. The consensus seems to be that this approach is encouraged because it documents the requirements on ‘T in an interface.

Leave a comment

Filed under C++, C++ Code, F#, Programming

How to define an interface with overloaded methods in F#

In F#, it’s possible to write both object-oriented and/or functional programs.  This means that a task that would be straight-forward in C++, defining an abstract interface containing overloaded methods, is also possible in F#.  However, you have to get the syntax exactly right, otherwise you get obscure compiler errors which could mis-lead you into thinking it isn’t possible after all.  For example, to use overloads, you must define multi-parameter methods using tuples.

type IBlog =
  abstract Write : DateTime * string * string -> IBlog
  abstract Write : string -> IBlog

type MusingStudio =
  interface IBlog with
    member this.Write (entryDate : DateTime, subject : string, body : string) =
      // publish blog entry
      (this :> IBlog)

    member this.Write (subject : string) =
      // automatically generate body and publish (!)
      (this :> IBlog)

Note the syntax of the abstract method declarations carefully.  As per this helpful post on StackOverflow, putting brackets around the tuple changes the signature and leads to confusing compiler errors:

type IBlog =
  abstract Write : (DateTime * string * string) -> IBlog // don't do this!
  abstract Write : string -> IBlog

Whilst it’s possible to implement the interface above and call into it, the syntax to do so involves additional brackets and is unnecessarily clunky.  The syntax at the top of this article is preferable:

let blog = WordPress( "MusingStudio") :> IBlog// create blog
blog
.Write( "How to overload in F#" )
.Write( DateTime.Now, "Book Review: Make Me, Lee Child", "Is this the best Jack Reacher so far?")

Leave a comment

Filed under F#, Programming

ACCU: Introducing Concepts for C++

Overload 129October 2015’s edition of Overload includes an excellent article by Andrew Sutton on Concepts for C++. I first heard about Concepts at the ACCU 2013 conference and it’s exciting to hear that they have reached Technical Specification stage.

There’s no doubt in my mind that concepts will play a huge role for those involved in generic programming. In F#, we already have the ability to state constraints on template arguments e.g. to ensure that ‘T satisfies the comparison constraint:

type Container<'T when 'T : comparison>( items : 'T[] ) =
    // ...

However, I wasn’t expecting the ability to use concepts for placeholders (so that, once you’ve defined a concept, you can use it where you might have used auto to gain the benefits of type deduction without the loss of information).

Leave a comment

Filed under C++, F#, Programming

Ten reasons (not) to use a functional programming language

Amusing tongue-in-cheek rant by FSharpForFunAndProfit about why you *should* use a functional programming language.

Leave a comment

Filed under F#

How to call methods with byref parameters from F#

When consuming C# libraries in F# projects, out parameters will be interpreted in F# with type byref. For example:

    public class Arithmetic
    {
        public static void sumAndDifference(
            int a, int b, out int sum, out int difference)
        {
            sum = a + b;
            difference = a - b;
        }
    }

Here, sumAndDifference has the following signature when the library is referenced from an F# project:
ByRef
The literal way to call the method is as follows, declaring reference value up-front and de-referencing them for use after the method call:

    let sum : int ref = ref 1
    let difference : int ref = ref 2
    Arithmetic.sumAndDifference(5, 3, sum, difference )
    printfn "Sum = %d, Difference = %d" !sum !difference

But F# also provides a much more concise syntax, allowing the out parameters to appear on the left hand side of an assignment:

    let sum, difference = Arithmetic.sumAndDifference(5, 3)
    printfn "Sum = %d, Difference = %d" sum difference

This syntax is so much cleaner and avoids any mention of references.

1 Comment

Filed under F#, Programming