Am trying to count down from 6 to 1 in a non-recursive factorial function and getting a compiler error:
let fact x =
let mutable product = 1
for i in x..-1..1 do
product <- product * i
product
// Error on the 6 - type 'int' does not support the operator '..-'
let answer = fact 6
printfn "%i" answer
I got this idea from near the bottom here
Have changed the function to just count up and it works, but I'm interested to know why this failed. Is there a better way to count down?
Using VS2012 update 3
Have changed the function to just count up and it works, but I'm interested to know why this failed.
Your example fails because ..
and -
are two different operators, the compiler needs separation between those. Instead of wrapping -1
by parentheses, you could add spaces:
let fact x =
let mutable product = 1
for i in x .. -1 .. 1 do
product <- product * i
product
Is there a better way to count down?
The less well-known for .. downto .. do
construct is more appropriate to use here.
let fact x =
let mutable product = 1
for i = x downto 1 do
product <- product * i
product
This works:
let fact x =
let mutable product = 1
for i in x..(-1)..1 do
product <- product * i
product
As does this (as used in the link in the question):
let fact x =
let mutable product = 1
for i in x .. -1 .. 1 do
product <- product * i
product
PS: also note that there are more functional ways to compute a factorial (bad to use mutable variables); the most obvious using recursion:
let rec fact x =
if x > 2
then x * (fact (x - 1))
else x
or a one-liner using lists:
let fact x = [2..x] |> List.reduce (*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With