I am trying to learn F#.
I wrote a function that factors out primes.
let PrimeFactors x =
let rec PrimeFactorsRecursive x div list =
if x % div = 0 then PrimeFactorsRecursive (x/div) div list @ [div]
elif div > int(System.Math.Sqrt(float(x))) then
if x > 1 then list @ [x]
else list
else PrimeFactorsRecursive x (div + 1) list
PrimeFactorsRecursive x 2 []
Now I am unsure if this is a good F# function or if it is more like “c#, written in f#”.
Is there a “more” functional way to write this code?
The primal problem in your code is that you use
@to concat two lists. Concating two lists costs linear time, not constant time.The constant way is to add the new prime number to the head of a list using
::operator as shown below:Also
letbind values are usually following camleStyle naming conversions.