1

我正在使用ref计数来计算函数执行的次数,但是如果我想摆脱 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}

但我想变得像

-: int = 2
4

2 回答 2

3

只需!then子句中添加 a 即可从 中提取值ref

let count =ref 0;;   
let rec addtive n= 
  if n<9 then !count
  else(
    incr count;
    addtive(sum(digit(n)))  
  ) ;;
于 2013-01-11T09:24:00.850 回答
0

您应该将计数作为第二个参数传递(如果需要,定义一个辅助方法):

let additive n =
  let rec helper n count =
    if n<9 then count
    else helper (sum (digit n)) (count + 1)
  in
  helper n 0
于 2013-01-10T20:36:04.193 回答