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