Rash thoughts about .NET, C#, F# and Dynamics NAV.


"Every solution will only lead to new problems."

Thursday, 2. July 2009


F# BootCamp – Questions and Answers – part IV – Structural comparison

Filed under: English posts,F# — Steffen Forkmann at 17:37 Uhr

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

No Comments »

No comments yet.

RSS feed for comments on this post. | TrackBack URI

Leave a comment

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> .