Lecture overview -- Keyboard shortcut: 'u'  Previous page: Iterative Control -- Keyboard shortcut: 'p'  Next page: State in Functional Programs -- 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 18 : 43

Assignments in Functional Programs

General use of assignment is hard to simulate in a functional program

Assignment for name binding purposes - single assignment - can be handled by name bindings in lambda expressions

Imperative

Functional - Scheme

void solveQuadraticEquation
             (double a, double b, double c){
  double discriminant, root1, root2;

  discriminant = b * b - 4 * a * c;

  if (discriminant < 0)
    printf("No roots\n");
  else if (discriminant == 0){
    root1 = -b/(2*a);
    printf("One root: %f\n", root1);
  }
  else {
    root1 = (-b + sqrt(discriminant))/(2*a);
    root2 = (-b - sqrt(discriminant))/(2*a);
    printf("Two roots: %f and %f\n", 
            root1, root2);
  }
}
(define (solveQuadraticEquation a b c)
  (let ((discriminant (- (* b b) (* 4 a c))))
    (cond ((< discriminant 0)
             (list))
          ((= discriminant 0)
             (let ((root1 (/ (- b) (* 2 a))))
               (list root1)))
          (else 
             (let ((root1 (/ (+ (- b) (sqrt discriminant))
                              (* 2 a)))
                   (root2 (/ (- (- b) (sqrt discriminant))
                              (* 2 a))))
               (list root1 root2))))))
void solveQuadraticEquation
             (double a, double b, double c){
  double discriminant = b * b - 4 * a * c;

  if (discriminant < 0)
    printf("No roots\n");
  else if (discriminant == 0){
    double root1 = -b/(2*a);
    printf("One root: %f\n", root1);
  }
  else {
    double root1 = (-b + sqrt(discriminant))/(2*a);
    double root2 = (-b - sqrt(discriminant))/(2*a);
    printf("Two roots: %f and %f\n", 
            root1, root2);
  }
}
Same