Download Introduction to the Objective Caml Programming Language

Transcript
13.4. CLASS INITIALIZERS
143
class linear_congruential_rng : ...
# rng#next_float;;
- : float = 0.292583613928950936
# rng#next;;
This expression has type linear_congruential_rng
It has no method next
13.4
Class initializers
Unlike many other object-oriented languages, OCaml does not provide explicit constructors.
With parameterized classes, there is less of a need, since the initial object can be often computed from
the parameters. However, there are times when it is useful or necessary to perform a computation
at object creation time.
There are two ways to specify initializers, as let-definitions that are evaluated before the object
is created, or as anonymous initializer methods that are evaluated after the object is created.
13.4.1
Let-initializers
Let-initializers are defined as the initial part of a class definition. Using our example, suppose
we wish to define a random number generator that produces either 1) a canonical sequence starting
from a standard seed, or 2) a sequence with a random initial seed. Our new generator will take a
Boolean argument, and use a let-definition to choose between the cases. For the latter case, we’ll
use the current time of day as the seed.
1
# class new_rng randomize_seed =
let a, c, m = 314159262, 1, 0x3fffffff in
let seed =
if randomize_seed
1 Note
that this example uses the Unix.gettimeofday function. To run the example in the toploop, you need to
pass the Unix library using the command ocaml unix.cma.