我在OCaml中编写了一个程序,它应该计算前100个Bell数。
这是我的代码(我使用Num
模块):
open Num
let one = num_of_int 1;;
let zero = num_of_int 0;;
计算阶乘:
let rec factorial n =
if n < 2
then one
else (num_of_int n) */ factorial(n-1)
计算牛顿:
let rec newton n k =
factorial n // (factorial k */ factorial (n-k))
let bell = Array.make 101 zero;;
bell.(0) <- one;;
bell.(1) <- one;;
let i = ref 2
let k = ref 0
let x = ref zero
let suma = ref zero
let n = ref 100
if !n != 0 || !n != 1 then
while !i <= !n do
while !k <= (!i-1) do
x := newton (!i-1) !k;
suma := !suma +/ (!x */ bell.(!k));
k := !k + 1
done;
bell.(int_of_num !k) <- (!suma);
suma:= zero;
k:=0;
i:= !i + 1;
done;;
bell.(int_of_num 20)
这是我用这种语言编写的第一个程序。编译时我遇到了一些问题。
答案 0 :(得分:0)
您错过了;;
的最后一个let n = ref 100
。但是,将全局变量用作算法的辅助变量,无论如何都被认为是不好的风格。下面的代码是对问题代码的最小修复,不认可坏样式的其他方面,例如不使用评论中提到的for
循环。
(* #load "nums.cma";; if in toplevel *)
open Num
let one = num_of_int 1;;
let zero = num_of_int 0;;
let rec factorial n =
if n < 2
then one
else (num_of_int n) */ factorial(n-1)
let rec newton n k =
factorial n // (factorial k */ factorial (n-k))
let bell input =
let bell = Array.make (input+1) zero in
bell.(0) <- one;
bell.(1) <- one;
let i = ref 2 in
let k = ref 0 in
let x = ref zero in
let suma = ref zero in
let n = ref input in
if !n <> 0 || !n <> 1 then
while !i <= !n do
while !k <= (!i-1) do
x := newton (!i-1) !k;
suma := !suma +/ (!x */ bell.(!k));
k := !k + 1
done;
bell.(!k) <- (!suma);
suma:= zero;
k:=0;
i:= !i + 1;
done;
bell.(input)