Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deferred evaluation in ocaml

Tags:

deferred

ocaml

I am following the example on page 107 of "Developing application with Objective-CAML".

type 'a v = Imm of 'a| Def of (unit -> 'a)

Now I am trying to understand how the constructor type Def enforces deferred evaluation? What does it mean to have Def parameterized with (unit -> 'a)?

like image 616
Ickyickyicky Ptangzoop Boing Avatar asked Dec 31 '25 18:12

Ickyickyicky Ptangzoop Boing


1 Answers

The type unit -> 'a represents a function. So the computation doesn't happen until you call the function. I.e., it's deferred.

The unit means that when you call the function you will pass () (a value of type unit, indeed the only value of the type).

the 'a means the function returns a value of the type given by the parameter of the type constructor v. So int v is the type of a deferred computation returning an int. And so on.

Update

Here is a value of type float v:

let deferred_float = Def (fun () -> sin 1.0)

Note that Def is not a type. It's a unary value constructor (like Some). It's often useful to think of Def as a function that takes a value of type unit -> 'a) and returns a value of type 'a v. Or you can think of it as a small tagged data structure that holds the function. In either case it's a value, not a type.

Here's how it looks in the toplevel:

# let deferred_float = Def (fun () -> sin 1.0);;
val deferred_float : float v = Def <fun>

If you imagine that it takes a long time (say a minute) to calculate sin 1.0, the point is that the value deferred_float is constructed more or less instantaneously. The computation of sin 1.0 is deferred until you actully call the contained function.

like image 118
Jeffrey Scofield Avatar answered Jan 04 '26 23:01

Jeffrey Scofield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!