Consider:
let mutable m' = m
while m' % i = 0L do
m' <- m' / i
I've refactored it into:
let m' =
let rec exhaust m =
if m % i = 0L then exhaust (m/i)
else m
exhaust m
but it's pretty obvious to me that the original code was way more concise and clear than this last one. Is there anything simple and clear that I'm missing regarding this refactor?
The full algorithm:
(* Calculates all the prime factors of a given integer *)
let primeFactors x =
let rec primeFactors' = function
| (m, _, r) when m = 1L -> r
| (m, i, r) ->
let mutable m' = m
while m' % i = 0L do
m' <- m' / i
primeFactors' (m', (i+1L), (if m <> m' then i::r else r))
List.rev (primeFactors' (x, 2L, []))