Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 1.21 KB  |  hits: 23  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Raise Unit of Measure type to specificed power
  2. let rec myPow(x:float<cm>,y:int) =
  3.     if y = 0 then x
  4.     else myPow(x*x, y - 1)
  5.        
  6. pow a 3 // Assuming a = 1.0<cm>, the return type is float<cm ^ 3>
  7. pow a n // Assuming a = 1.0<cm>, the return type is float<cm ^ n>
  8.        
  9. [<Measure>] type cm
  10.  
  11. // Represents a number with units of measure powered to the
  12. // number's value (e.g "(S (S O))" has type Num<cm, cm^3>)
  13. type Num<[<Measure>] 'M, [<Measure>] 'N> =
  14.   | O_ of int * float<'N>
  15.   | S_ of int * Num<'M, 'N / 'M>
  16.  
  17. // Constructors that hide that simplify the creation  
  18. let O : Num<'M, 'M> = O_ (1, 0.0<_>)
  19. let S n = match n with O_(i, _) | S_(i, _) -> S_(i + 1, n)
  20.  
  21. // Type-safe power function with units of measure
  22. let pow (x:float<'M>) ((O_(i, _) | S_(i, _)):Num<'M, 'M 'N>) : float<'M 'N> =
  23.   // Unsafe hacky implementation, which is hidden
  24.   // from the user (for simplicity)
  25.   unbox ((float x) ** float i)
  26.  
  27. let res = pow 2.0<cm> (S (S O))
  28.        
  29. let inline pow2 (x: float<'a>) : float<'a^2> = pown (float x) 2 * 1.<_>
  30. let inline pow3 (x: float<'a>) : float<'a^3> = pown (float x) 3 * 1.<_>
  31. let inline pow4 (x: float<'a>) : float<'a^4> = pown (float x) 4 * 1.<_>
  32. let inline pow5 (x: float<'a>) : float<'a^5> = pown (float x) 5 * 1.<_>