Equality checking in F#

F# uses the equality sign ‘=’ to check for equality like here:

let areTheyEqual = 5 = 5

areTheyEqual will evaluate to true. At first it can be confusing to see the two single equality signs like that. The first one is the assignment operator and the second one checks for equality. It might be easier to rewrite the above as follows:

let areTheyEqual = (5 = 5)

The equality operator in F# checks for value equality for value types. It’s easy to check for equality on lists, arrays, tuples etc. Here are a couple of examples:

let myList = [1..10]
let myListTwo = [1..10]
let areListsEqual = myList = myListTwo

let myArray = [|1;3;5;7;9|]
let myArrayTwo = [|1;3;5;7;9|]
let areArraysEqual = myArray = myArrayTwo

let hello = "hello";
let helloAgain = "hello";
let areStringsEqual = hello = helloAgain

type Address = {
    street: string;
    city: string;
    number: int;
}

let myAddress = {street = "New Street"; number = 32; city = "Birmingham"}
let herAddress = {street = "New Street"; number = 32; city = "Birmingham"}
let areAddressesEqual = myAddress = herAddress

areListsEqual, areArraysEqual, areStringsEqual, areAddressesEqual will all be true since their constituent values are equal.

However, for reference types equality is based on reference equality by default. Consider the following Order class:

type Order (product:string, value: int) =
    member this.Product = product
    member this.Value = value

…and the following comparisons:

let orderOne = Order("book", 500)
let orderTwo = Order("book", 500);
let areOrdersEqual = orderOne = orderTwo
let orderOneRefCopy = orderOne
let areReferencesEqual = orderOne = orderOneRefCopy

areReferencesEqual will be true since orderOne and orderOneRefCopy point to the same instance of Order. However, areOrdersEqual will be false even if orderOne and orderTwo have the same values. Since they point two distinct Order instances equality checking will yield false.

View all F# related articles here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: