Peng Zang < peng.zang%40gmail.com">peng.zang
gmail.com> writes:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> I forget what this kind of recursion is called and I cannot seem to get it to
> work.
>
> Here is an (failing) example for a function that counts how many times it has
> been called with an even argument:
>
> let numeven b =
> let rec aux a b =
> (a, aux (if b mod 2 = 0 then a + 1 else a))
> in aux 0
>
> It errors with: This expression has type int * (int -> int * 'a) but is here
> used with type int * 'a
>
> I know I can write a side-effecting version using a hidden ref, but I need a
> functional version. Does any one know how do you do this in OCaml and what
> is this type of thing is called?
Enable recursive type, if that's what you really want.
$ ocaml -rectypes
Objective Caml version 3.09.2
# let numeven b =
let rec aux a b =
(a, aux (if b mod 2 = 0 then a + 1 else a)) in
aux 0;;
val numeven : 'a -> (int -> int * 'b as 'b) = <fun>
.