Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

Browse thread
Iteration over Data constructors
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-05-06 (09:58)
From: Warp <warplayer@f...>
Subject: Re: "ocaml_beginners"::[] Iteration over Data constructors
> Hi All,
>
> I have a type
>
> type testTyp = First | Second | Third | Umpteenth
>
> Is there a library function with the following behavior?
>
> f (First) = Second
> f (Second) = Third
> f (Third) = Umpteenth
> f (Umpteenth) = <exception>
>
> Basically, I want the function to return the next data constructor of
> this type. The order of data constructors does not matter (need not be
> the same as they are defined) as long as the results are consistent
> for multiple runs.
>
> Thanks,

You can trick by doing ( only if your constructors does not have any
parameters ) :

let f x = (Obj.magic ((Obj.magic x : int) + 1) : 'a)

but that won't raise an exception on constructor number overflow ( that
behavior does depend of the number of constructors of your type ) - you can
also enforce f as 'a -> 'a

Nicolas Cannasse