“这不是函数;无法应用”错误是什么意思?

问题描述

我对 OCaml 很陌生,但遇到了这个错误

 let n = read_int ()
    let rec pi  = 
  match n with
  | _ when n < 0 || n > 10000 -> raise (Failure "pi")
  | 1 -> 2. *. ((2. *. 2.) /. (1. *. 3.))
  | _ -> float_of_int (n * n * 2 * 2) /. float_of_int ((2 * n - 1) * (2 * n + 1)) *. pi (n - 1)
This expression has type float
       This is not a function; it cannot be applied.

代码在没有 read_int () 的情况下工作,但在这种情况下我需要 read_int

解决方法

没有争论

 let rec pi =

您定义的不是递归函数,而是递归值 pi(恰好是浮点数)。因此,当您尝试将此浮点 pi 用作函数时,编译器会引发错误

6 |   | _ -> float_of_int (n * n * 2 * 2) /. float_of_int ((2 * n - 1) * (2 * n + 1)) *. pi (n - 1)
                                                                                         ^^
Error: This expression has type float
       This is not a function; it cannot be applied.

您需要先将 pi 定义为函数。一旦定义了这个函数,你就可以在你的输入值上调用它。

,

如果你查看你的代码,你可以看到:

 let n = read_int ()
    let rec pi  = 
      match n with
      | _ when n < 0 || n > 10000 -> raise (Failure "pi")
      | 1 -> 2. *. ((2. *. 2.) /. (1. *. 3.))
      | _ -> float_of_int (n * n * 2 * 2) /. float_of_int ((2 * n - 1) * (2 * n + 1)) *. pi   (n - 1)

pi 不是函数,而是值。由于 pi 不接受任何参数。一个可能的解决方法是将 "n" 作为参数:

let rec pi n = 
  match n with
  | _ when n < 0 || n > 10000 -> raise (Failure "pi")
  | 1 -> 2. *. ((2. *. 2.) /. (1. *. 3.))
  | _ -> float_of_int (n * n * 2 * 2) /. float_of_int ((2 * n - 1) * (2 * n + 1)) *. pi   (n - 1)