函数式编程 - F# 失败,"Error 4 This expression was expected to have type int but here has type int -> int



这是我试图得到工作的最后一行是它失败的代码:

let rec gcd a b =
    if b= 0 then
        a
    else
        gcd b (a % b);;
let n = 8051
let mutable d = 0
let mutable c = 1
let mutable xi = 2
let mutable yi = 2
let f x = (pown x 2) + (c % n);;
while c < 100 do
    while d = 1 do
        xi <- (f xi)
        yi <- (f(f(yi)))
        printfn "%d%d" xi yi        
        d <- gcd(abs (xi - yi) n)

--------------------- 下面的代码工作;除了N上的整数溢出---------

module Factorization

let rec gcd a b =
    if b= 0 then
        a
    else
        gcd b (a % b);;
let n = 600851475143N
let mutable d, c, xi, yi = 1, 1, 2, 2
let f x = (pown x 2) + (c % n);;
let maxN m =int(ceil(sqrt(float m)))
//if (n > maxN(xi)) && (n >  maxN(yi)) then
while c < 100 do
    d <- 1
    while d = 1 do        
        if (maxN(n) > xi) && (maxN(n) >  yi) then
            xi <- f xi
            yi <- f(f(yi))           
            d <- gcd (abs (xi - yi)) n
            //fail
            if d = n then d<-1
            if d <> 1 then printfn "A prime factor of %d x = %d,  y = %d, d = %d" n xi yi d
        else
            xi <- 2
            yi <- 2
            c  <- c + 1;;

除了@Rangoric指出的,外括号也必须删除,否则curry将无法工作:

d <- gcd (abs(xi-yi)) n

哎呀,这里有一些不请自来的提示(@BrokenGlass正确地回答了这个问题)。

首先,您可以在一行中分配所有这些变量:

let mutable d, c, xi, yi = 0, 1, 2, 2

第二,少用圆括号:

xi <- f xi
yi <- f (f yi)

当然,尽量避免变量和while循环。但我将把它留给你,因为我相信你已经意识到你使用递归实现了gcd

尝试:

d <- gcd (abs(xi-yi)) n

指出abs是int->int型,而本身不是int型。将它包装在括号中导致abs在gcd查看它之前被执行。这将导致gcd看到abs的结果,而不是abs本身。

最新更新