List Info

Thread: "ocaml_beginners"::[] Re: why does this recursion not work?




"ocaml_beginners"::[] Re: why does this recursion not work?
country flaguser name
Norway
2007-05-31 16:24:00


Peng Zang < peng.zang%40gmail.com">peng.zanggmail.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.
&gt;
> Here is an (failing) example for a function that counts how many times it has
> been called with an even argument:
>
&gt; 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>;

__._,_.___
.

__,_._,___
[1]

about | contact  Other archives ( Real Estate discussion Medical topics )