3

Consider the following F# code:

[<Measure>] type pixel
[<Measure>] type inch
[<Measure>] type dot
[<Measure>] type percentage

let scaleCalculation (finalSize:float<pixel>) (originalSize:float<pixel>) =
   finalSize/originalSize * 100.0<percentage>

(I realize I need to check originalSize for 0 but that's not really germaine to this question).

What I'd like is to overload this function to handle inches and dots per inch. I don't think there's any way to overload on the unit of measure but I just thought I'd see if anyone had any suggestions on this.

I know I could do this:

   let scaleCalculation (finalSize:float) (originalSize:float) =
      finalSize/originalSize * 100.0<percentage>

but then I lose checking on the measure of finalSize and originalSize. I just want to insure that the measure of finalSize and originalSize are the same.

Any suggestions, thoughts?

Onorio Catenacci
  • 14,928
  • 14
  • 81
  • 132

1 Answers1

8
let scaleCalculation (finalSize:float<'u>) (originalSize:float<'u>) =
   finalSize/originalSize * 100.0<percentage>

Units of Measure in F#: Part Four, Parameterized Types

Benjol
  • 63,995
  • 54
  • 186
  • 268
gradbot
  • 13,732
  • 5
  • 36
  • 69
  • Absolutely excellent. I figured I'd need to use a generic somehow but hadn't quite got to trying out the code just yet. Thanks Gradbot. Hey are you on Google+ yet? – Onorio Catenacci Jul 14 '11 at 23:54
  • And I wish I could give you another upvote for that link. :-) – Onorio Catenacci Jul 15 '11 at 00:01
  • @Benjol--why did you modify that code? I mean as far as I can tell you changed the generic 'a to 'u--I don't quite follow how that's improving the code. Also, if you're going to change the letter of the generic parameter 'm would make more sense to me. 'm as in "Measure". :-) – Onorio Catenacci Jul 16 '11 at 05:31
  • @Onorio `'u` is consistent with the style used in fsharps source code. I assume it stands for unit of measure. – gradbot Jul 16 '11 at 20:50