f# - Raise Unit of Measure type to specificed power -


is possible somehow create pow function measure types? pow function in f# takes int parameter, , pow function in math class takes float - dosent allow float<cm>.

i first thought that:

let rec mypow(x:float<cm>,y:int) =     if y = 0 x     else mypow(x*x, y - 1) 

might work out, obvious each time come across else line change return type.

any suggestions?

ankur correct - cannot (without resorting hacks break units).

maybe clearer description of problem type of pow function depend on value of argument , f# doesn't allow this. imagine work if using literals second argument, become tricky if used expressions:

pow 3 // assuming = 1.0<cm>, return type float<cm ^ 3> pow n // assuming = 1.0<cm>, return type float<cm ^ n> 

in second case value n have appear in type!

you can use nasty tricks (inspired haskell article), becomes bit crazy. instead of using numeric literals, you'd use s(s(s(n))) represent number 3. way, can bring number type. don't want this, here example:

[<measure>] type cm  // represents number units of measure powered // number's value (e.g "(s (s o))" has type num<cm, cm^3>) type num<[<measure>] 'm, [<measure>] 'n> =    | o_ of int * float<'n>   | s_ of int * num<'m, 'n / 'm>  // constructors hide simplify creation   let o : num<'m, 'm> = o_ (1, 0.0<_>) let s n = match n o_(i, _) | s_(i, _) -> s_(i + 1, n)  // type-safe power function units of measure let pow (x:float<'m>) ((o_(i, _) | s_(i, _)):num<'m, 'm 'n>) : float<'m 'n> =   // unsafe hacky implementation, hidden   // user (for simplicity)   unbox ((float x) ** float i)  let res = pow 2.0<cm> (s (s o)) 

edit: posted source code f# snippets, can see inferred types: http://fssnip.net/4h


Comments

Popular posts from this blog

Cursor error with postgresql, pgpool and php -

delphi - ESC/P programming! -

c++ - error: use of deleted function -