Lecture overview -- Keyboard shortcut: 'u'  Previous page: State in Functional Programs -- Keyboard shortcut: 'p'  Next page: Continuations [Section] -- Keyboard shortcut: 'n'  Lecture notes - all slides together  Annotated slide -- Keyboard shortcut: 't'  Alphabetic index  Help page about these notes  Course home    Simulation of other Paradigms and Continuations - slide 20 : 43

Object Mutation

Object mutation in imperative programming (or object-oriented programming) can be dealt with by functions that return a mutated copy of the object.

Imperative

Functional - Scheme

#include 

struct point{
  double x, y;
};

typedef struct point point;

void move(point *p, double dx, double dy){
  p->x += dx;
  p->y += dy;
}

int main(void) {
  point p = {5.0, 7.0};

  printf("p: (%lf, %lf)\n", p.x, p.y);
  move(&p, 1.0, 2.0);
  printf("p: (%lf, %lf)\n", p.x, p.y);

  return 0;
}
(define (make-point x y)
  (list 'point x y))

(define point-x (compose car cdr))

(define point-y (compose car (compose cdr cdr)))

(define p (make-point 5.0 7.0))

(define (move p dx dy)
  (make-point (+ (point-x p) dx) (+ (point-y p) dy)))

> p
 (point 5.0 7.0)

> (define q (move p 1 2))

> q
(point 6.0  9.0)