Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# For loop negative count down - Type int does not support the operator ..-

Tags:

f#

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

like image 237
Dave Mateer Avatar asked Jul 30 '13 16:07

Dave Mateer


2 Answers

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
like image 169
pad Avatar answered Sep 30 '22 15:09

pad


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 (*)
like image 34
Jwosty Avatar answered Sep 30 '22 15:09

Jwosty