This is the third part in a “Questions and Answers”-series about the F# BootCamp in Leipzig. This time we will look at structural comparison and structural equality.
Question 6: Please describe the terms “Structural Comparison” and “Structural Equality”.
This was a simple question. Basically the answer is F# provides a default implementation for IComparable and .Equals() for all custom types. This default implementation compares all public fields of the two instances. Let’s consider some samples:
Tuples
let a = 3,4,"foo" let b = 3,4,"bar" printfn "a > b = %b" (a > b) // true printfn "a < b = %b" (a < b) // false
Records
type MySimpleRecord = { a: int; b: int;} type MyCompositeRecord = { x: string; y: int; z: MySimpleRecord} let a = { x = "Test"; y = 3; z = {a = 1; b = 4;}} let b = { x = "Test"; y = 3; z = {a = 1; b = 2;}} // Structural comparison printfn "a > b = %b" (a > b) // true printfn "a < b = %b" (a < b) // false printfn "Min(a,b) = %A" (min a b) printfn "compare(a,b) = %d" (compare a b)
Lists
let a = [3; 2; 4; 5] let b = [3; 2; 4; 3; 3] // Structural comparison printfn "a > b = %b" (a > b) // true printfn "a < b = %b" (a < b) // false printfn "Min(a,b) = %A" (min a b) printfn "compare(a,b) = %d" (compare a b)Tags: .NET User Group Leipzig, F#, Functional Programming