Big_int阶乘异常

时间:2016-06-05 15:31:43

标签: ocaml

我尝试使用Big_int实现阶乘,utop可以对其进行评估,但在运行时失败。这是代码:

let factorial (num : int) =
  let n = Big_int.big_int_of_int num in
  let rec fac (n : Big_int.big_int) : Big_int.big_int =
  if n = Big_int.zero_big_int then Big_int.unit_big_int
  else Big_int.mult_big_int n (fac (Big_int.sub_big_int n Big_int.unit_big_int)) in
  fac n

如何解决此案?使用Big_int实现阶乘的正确(和简短)方法是什么?
运行此代码:factorial 3 ;;
错误输出:

Exception: (Invalid_argument "compare: abstract value").
Raised by primitive operation at file "//toplevel//", line 4, characters 5-29
Called from file "//toplevel//", line 5, characters 30-80
Called from file "//toplevel//", line 5, characters 30-80
Called from file "//toplevel//", line 5, characters 30-80
Called from file "toplevel/toploop.ml", line 180, characters 17-56

1 个答案:

答案 0 :(得分:1)

问题在于此比较function test(x::Symbol(:ALPHA)) end function test(x::Symbol(:BETA)) end 。如果您将其更改为使用n = Big_int.zero_big_int的函数进行比较Big_int s - big_int,那么一切都应该有效。

这是实现使用尾递归的此函数的另一个示例:

eq_big_int

open Big_int let factorial (num : int) : big_int = let rec fac_big_int n acc = if n = 0 then acc else fac_big_int (pred n) (mult_big_int (big_int_of_int n) acc) in fac_big_int num unit_big_int 中的测试:

utop