Equality checking in F#
March 18, 2017 Leave a comment
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.