Pages

Thursday, December 29, 2011

F# ≥ C# (Units of Measure II)


During the Christmas party, I heard a story about my friend got a ticket in Canada. The reason is simple: he drove 100 miles/hour in Ontario Canada where the speed limit is 100 km/hour. :-(

The fine for his case could be $10,000. Fortunately he did not get that scary number on his ticket, but still cost him a fortune.

When I was listening to his story, I realize how important the unit is and how nice F# provide such a feature. Other than the sample in the previous post, the following code snippet shows how a point class can have a unit with it, so that I can define a point class with "cm" unit, I believe this is very useful when doing scientific computation.

[ < Measure > ] type cm
type Point< [ < Measure > ] 't>(x:int< 't >,y:int< 't >) =
    member val X = x with get,set
    member val Y = y with get,set
    static member ( * ) (a:Point<_>,b:int) = Point(b*a.X,b*a.Y) 
let a = Point< cm >(1< cm >, 1< cm >)
a.X <- 3 < cm > 
printfn "%A" a.X
let c = a * 4


No comments: