CS253: Software Development with C++

Fall 2022

Programming Paradigms

Show Lecture.ProgrammingParadigms as a slide show.

CS253 Programming Paradigms

Overview

Imperative programming

Declarative programming

Functional programming example

Parallel JavaScript implementations, taken from Wikipedia:

// Imperative style
const numList = [1, 2, 3, 4, 5, 6, 7, 8];
let result = 0;
for (let i = 0; i < numList.length; i++) {
  if (numList[i] % 2 === 0) {
    result += numList[i] * 10;
  }
}
// Functional style
const result = [1, 2, 3, 4, 5, 6, 7, 8]
               .filter(n => n % 2 === 0)
               .map(a => a * 10)
               .reduce((a, b) => a + b);
 
 
 

Sure, down at the machine instruction level, it’s all imperative. However, the programmer doesn’t have to think that way. You don’t have to think about the mechanics of looping. Instead you think about transforming the data.

C++ declarative programming

array a{18,19,20,21,22,23,24,25,26,27,28};
int sum = 0;
// imperative loop:
for (size_t i=0; i<a.size(); i++)
    sum += a[i];
cout << sum;
253
array a{18,19,20,21,22,23,24,25,26,27,28};
int sum = 0;
// declarative loop:
for (int n : a)
    sum += n;
cout << sum;
253

Event-driven programming

Clock example

An imperative clock program might work like this pseudocode:

int main() {
    while (true) {
        sleepms(1000);
        display_time();
    }
}

Or, it might be event-driven, where the event is a clock triggering:

int main() {
    schedule_periodic_callback(1000, &display_time);
    do_nothing_but_service_interrupts();
}

The event-driven code could be easily modified to handle other event-driven tasks: keyboard input, mouse clicks, etc.