开发者

ocaml - function without args and global variables

I have a task to do in ocaml and can't find any help information so ask here ;) How to define fun开发者_开发知识库ction which give us something other in each call without using global variables ? I would like to do fun next() which return next odd numbers or next values of factorial.

Like this

# next();;
- : int = 1
# next();;
- : int = 3
# next();;
- : int = 5
# next();;
- : int = 7

Do you have any tips for me ?

Thanks in advance

Greg


let next =
  let private_counter = ref (-1) in
  fun () ->
    private_counter := !private_counter + 2;
    !private_counter

You can also encapsulate this in a "counter factory":

let make_counter () =
  (* note the () parameter : at each call of make_counter(),
     a new "next function" with a fresh counter is generated *)
  let private_counter = ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜