State

In computer science

An object "has state" if its behaviour depends on its history. eg. a bank account object (can be characterized by a single state variable - current balance that summarizes its entire history). Implementation of state requires an assignment operator. In Lisp, this is given by

(set! <name> <new-value>)

with an arbitrary returned value.

Data objects are therefore, made mutable, in order to make them stateful. For pairs (constructed in Scheme using cons, car and cdr), the primitive mutators are set-car! and set-cdr!, which in turn help to mutate compound data objects. We could even define cons in terms of the two mutators along with an implementational primitive get-new-pair that handles memory allocation etc:

(define (cons x y)
	(let ((new (get-new-pair)))
		(set-car! new x)
		(set-cdr! new y)
		new))

Typically, we want to hide the state variables and protect them from external changes or expose them only on a need-to-know basis - Encapsulation.

By definition, mutability leads to loss of referential transparency.


Links

Sources