Tag Archives: F#

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

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()


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

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:
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

How to write optional parameters in F# with default values

Question: What’s the difference between

let f ( a : int option, b : string option ) = ...


let f ( ?a : int, ?b : string ) = ...

Answer: in the first example, even if you have no values for a and b, you must call

let ret = f ( None, None )

whereas in the second example, you can simplify matters:

let ret = f ()

But what if you want to supply default values for those optional parameters? Here’s an example of a type definition in which the constructor takes optional parameters and assigns them default values if no value has been supplied. defaultArg is an F# operator, not a locally defined function.

type T( ?a : int, ?b : string ) =
  let a = defaultArg a 42
  let b = defaultArg b "Hello, World"

Whilst this syntax seems rather clunky, it is effective. You can read more about it on MSDN (scroll down to the section “Optional Parameters”).

Leave a comment

Filed under Programming

Surge in popularity of F#

InfoWorld reports that F# is becoming ever more popular. It has risen from 69th to 12th in the Tiobe Programming Community Index.

I’ve been writing F# code for over 3 years and I get the appeal – there are some algorithms that are so much easier to implement in F# than in C++ (particularly when they can be neatly expressed with the additional data structures that F# provides, like discriminated unions).

Leave a comment

Filed under Programming

F# Software Foundation

The F# community has founded a new organisation to promote the use of F# – FSSF

The mission of the F# Software Foundation is to promote, protect, and advance the F# programming language, and to support and facilitate the growth of a diverse and international community of F# programmers.

1 Comment

Filed under Programming

Benefits of functional programming

A couple of linked articles with a strong story on the benefits of choosing F# over C# for reducing the bug count and reducing the size of the codebase.

Simon Tyler Cousins compares two similar projects with F# clearly superior to C# in every category for those projects.

Don Syme opines that a key benefit of F# is that nulls are all but eliminated in the code and references the manifesto for Not Only O-O:

We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value:

Functions and Types over classes
Purity over mutability
Composition over inheritance
Higher-order functions over method dispatch
Options over nulls

That is, while there is value in the items on the right (except for nulls), we value the items on the left more.

Leave a comment

Filed under Programming

Equality and Comparisons in F#

This blog post from Don Syme is really useful when considering options for customising equality and comparisons in F#. Having said that, with F# 2.0, it looks like you don’t need to put attributes on your type, it’s enough to follow Don’s overrides of GetHashCode, Equals and CompareTo.

Leave a comment

Filed under Programming

Bjarne Stroustrup’s Tour of C++

I’m reading through Bjarne Stroustrup’s Tour of C++, which Addison-Wesley have graciously allowed him to post ahead of its inclusion in the fourth edition of The C++ Programming Language.


It starts with The Basics. It was refreshing to see new features of C++11 introduced alongside the most rudimentary aspects of the language – rather than being viewed as a whole new language that teams might choose to adopt/ignore. I’m sure if you start learning C++ today, features such as enum class, auto, constexpr will seem natural, begging the question “What did you do without them?”.

I thought this code snippet was especially cute:

for (auto x : {10,21,32,43,54,65})
    std::cout << x << '\n';

I’m used to writing code in F# like this,

[| 10; 21; 32; 43; 54; 65 |] 
  |> Array.iter (fun i -> printf "%d\n" i)

but it’s great to see such concise code in C++ at well.

The second part concerns abstractions. This includes summaries of copy and move semantics. This note on move semantics is helpful because many explanations focus on how to move data into a new instance of a class rather than the state in which to leave the old object:

After a move, an object should be in a state that allows a destructor to be run. Typi- cally, we should also allow assignment to a moved-from object

Preventing copy and move:

Using the default copy or move for a class in a hierarchy is typically a disaster: Given only a pointer to a base, we simply don’t know what members the derived class has (§3.3.3), so we can’t know how to copy them. So, the best thing to do is usually to delete the default copy and move operations; that is, to eliminate to default definitions of those two operations

where C++11 provides the delete annotation to tell the compiler not to write a default copy/move operation, but you could follow today’s practice and declare it private and omit the implementation until your compiler catches up.

If you need to copy an object in a class hierarchy, write some kind of clone function. [Note that] a move operation is not implicitly generated for a class where the user has explicitly declared a destructor. Furthermore, the generation of copy operations are deprecated in this case. This can be a good reason to explicitly define a destructor even where the compiler would have implicitly provided one.

There are also useful examples of where to use type aliasing, for example this one that uses the assumption that STL containers provide a value_type alias (or typedef):

template<typename C>
using Element_type = typename C::value_type; 

template<typename Container> void algo(Container& c)
  Vector<Element_type<Container>> vec;
  // ... 

You can also use aliasing to define new templates by binding arguments on existing templates:

template<typename Value>
using String_map = Map<string,Value>;

String_map<int>m; //alias for Map<string,int>

Part three is about algorithms and containers.

The example for how to write operator>>(), read from, is particularly verbose – I’m sure it would have been better to show a regex solution alongside. Worth a look anyway for this mechanism for indicating a streaming failure (typically I would throw an exception):


Similarly, I hadn’t realised before that range-checked random access to a std::vector was possible via the at(size_t i) method:

T& operator[](int i) { return vector::at(i); } // range-checked

The final part is about concurrency and utilities.

One of the main utilities now available in C++11 is std::shared_ptr (which was sorely lacking from the previous standard).  However, Stroustrup hints that in many cases it’s sufficient to create an object on the stack with a local variable:

Unfortunately, overuse of new (and of pointers and references) seems to be an increasing problem.

When you do need to manage heap objects, std::unique_ptr is very lightweight with no space or time overhead compared to a built-in pointer.  You can pass or return unique_ptr’s in or out of functions, because the implementation uses move semantics (whereas std::shared_ptr is copied).

One concurrency topic that always causes problems is how to define a convention between locks so that deadlock cannot occur due to acquiring the locks in the wrong order.  There’s a neat example of how to avoid that:

// Initialise lock guards with their mutexes, but don't lock yet
std::lock_guard<std::mutex> lock1(mutex1, defer_lock);
std::lock_guard<std::mutex> lock2(mutex2, defer_lock);
std::lock_guard<std::mutex> lock3(mutex3, defer_lock);
// other preparation
std::lock( lock1, lock2, lock3 );
// Implicitly release all mutexes when locks go out of scope.

Stroustrup also introduces the concepts of futures and promises:

The important point about future and promise is that they enable a transfer of a value between two tasks without explicit use of a lock; “the system” implements the transfer efficiently.

The absence of locks is key and is also mentioned when introducing std::packaged_task and std::async.  This section might be better written in reverse, with the simpler async concept introduced first and locks/mutexes in context as the advanced technique.

Under <utilities>, a boon is likely to be std::tuple, a heterogenous sequence of elements (I’ve added the use of std::tie to show how to unpack the values):

auto myTuple = std::make_tuple(std::string("Hello"), 10, 1.23);
std::string a;
int b;
double c;
std::tie( a, b, c ) = myTuple;

I wouldn’t use std::tuple in an externally visible interface, but it’s useful to avoid defining types for passing multiple return values.

I like this example of using the new standard <random> library to simulate a die:

using my_engine = default_random_engine; // type of engine
using my_distribution = uniform_int_distribution<>; 
my_engine re {}; // the default engine
my_distribution one_to_six {1,6}; 
auto dice = bind(one_to_six,re); // make a generator
int x = dice(); // roll the dice: x becomes a value in [1:6]


Leave a comment

Filed under C++