Is it possible to somehow create a pow function for measure types?
The pow function in f# only takes int as parameter, and then pow function in the Math class takes a float – but dosent allow float<cm>.
I first thought that:
let rec myPow(x:float<cm>,y:int) =
if y = 0 then x
else myPow(x*x, y - 1)
might work out, but its obvious that each time it come across the else line it will change the return type.
Any suggestions?
Ankur is correct – you cannot do this (without resorting to hacks that would break units).
Maybe a clearer description of the problem is that the type of
powfunction would depend on the value of the argument and F# doesn’t allow you to do this. You could imagine this would work if were using just literals as the second argument, but it would become tricky if you used expressions:In the second case the value
nwould have to appear in the type!You can use some nasty tricks (inspired by this Haskell article), but it becomes a bit crazy. Instead of using numeric literals, you’d use something like
S(S(S(N)))to represent the number3. This way, you can bring the number into the type. You probably don’t want to do this, but here is an example:EDIT: I posted the source code to F# snippets, so that you can see the inferred types: http://fssnip.net/4H