In OCaml, a Lazy value is an expression that is evaluated only when its value is needed. This can be useful for avoiding the unnecessary evaluation of costly operations, or for defining potentially infinite data structures.

The Lazy module provides a t type that represents a lazy value. This type is used to wrap an expression that is not immediately evaluated. When the value is needed, it is evaluated and the result is cached so that it does not need to be computed again. This means that the same expression can be evaluated many times without incurring the cost of recomputing it.

type 'a stream = {
  hd : 'a;
  tl : 'a stream Lazy.t;
}

let rec repeat (a : 'a) : 'a stream =
  {
    hd = a;
    tl = lazy (repeat a);
  }

In the above example, the repeat function generates an infinite stream of repeated values.

The tl field of the stream type is defined using a Lazy value. Instead of directly calling the repeat function recursively to compute the next element of the stream, the recursive call is wrapped in a lazy expression. This means that the computation is not performed until the tl field is accessed, which allows for potentially infinite streams to be defined.

let r = repeat "a" ;;
val r : string stream = {hd = "a"; tl = <lazy>}

r.hd ;;
- : string = "a"

Lazy.force r.tl ;;
- : string stream = {hd = "a"; tl = <lazy>}

Lazy.force r.tl evaluates the lazy expression stored in r.tl, which is of type string stream Lazy.t, and returns the corresponding string stream value with the head "a" and a lazy tail <lazy>.