ocaml循环计数是否不使用ref计数?

ocaml循环计数是否不使用ref计数?,ocaml,Ocaml,我使用refcount来计算函数执行的次数,但是如果我想去掉ref呢?我是ocaml的不速之客,请给我一些建议,以下是我得到的: let count =ref 0;; let rec addtive n= if n<9 then count else( incr count; addtive(sum(digit(n))) ) ;; # a 551515;; - : int ref = {contents = 2} 您应该将计数作为第二个参数传递(如有必要,请定

我使用
ref
count来计算函数执行的次数,但是如果我想去掉ref呢?我是ocaml的不速之客,请给我一些建议,以下是我得到的:

let count =ref 0;;  
let rec addtive n=
if n<9 then count 
else(
     incr count;
     addtive(sum(digit(n)))
) ;;

# a 551515;;
- : int ref = {contents = 2}

您应该将计数作为第二个参数传递(如有必要,请定义帮助器方法):

n=
让rec helper n计数=

如果n只需添加一个
然后
子句中的code>,从
ref
中提取值:

let count =ref 0;;   
let rec addtive n= 
  if n<9 then !count
  else(
    incr count;
    addtive(sum(digit(n)))  
  ) ;;
let count=ref 0;;
让rec additive n=

如果这里有一个助手,我有3个函数调用,a,s,di应该使它更好,我有ediited@user1968057我定义了一个helper方法,因此
a
方法仍然只接受一个参数。如果没有必要,您就不需要助手,而是通过递归(注意let rec)在函数参数中传递新值,而不是变异变量。当终止条件为true时,返回该值。这是OCaml中的通用技术,因此您应该非常熟悉它。将helper设置为顶级函数,如果仍然不清楚,则使用#trace调用它。@user1968057这不是OCaml特有的。我所做的只是定义一个helper函数,它接受两个参数而不是一个参数,并将计数作为第二个参数传递。然后,1参数函数调用2参数函数,参数为0。在类似C的语言中,这看起来是这样的:“但是我想得到-:int=2”只要更改
。。。然后计数到
。。。那么!计数
let additive n =
  let rec helper n count =
    if n<9 then count
    else helper (sum (digit n)) (count + 1)
  in
  helper n 0
let count =ref 0;;   
let rec addtive n= 
  if n<9 then !count
  else(
    incr count;
    addtive(sum(digit(n)))  
  ) ;;