【问题标题】:F# fails with "Error 4 This expression was expected to have type int but here has type int -> int"F# 失败并显示“错误 4 此表达式应具有 int 类型,但此处具有 int -> int 类型”
【发布时间】:2011-04-22 01:56:39
【问题描述】:

这是我试图开始工作的代码,最后一行是它失败的地方:

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;;

【问题讨论】:

  • 我认为您永远不会执行最后一行,因为您正在将 d 初始化为 0 但正在执行 while d = 1 :)
  • 有趣的是,他不会经常无限地执行最后一行,因为 c 永远不会改变,所以仍然是 1,即

标签: f# functional-programming


【解决方案1】:

除了@Rangoric 指出的,外括号也必须去掉,否则柯里化将不起作用:

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

【讨论】:

  • 这就是我所缺少的!谢谢
【解决方案2】:

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

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

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

其次,在括号上放轻松:

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

当然,还要尝试摆脱可变变量和 while 循环。但我将把它留给你,因为我确定你知道看到你使用递归实现了gcd

【讨论】:

    【解决方案3】:

    试试:

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

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

    【讨论】:

    • 我在发布之前尝试过,但它不起作用:(我得出的结论是它返回的是一个函数而不是一个值。我尝试了以下方法:d
    • 删除了括号,这就是我没有先尝试的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多