Table of Contents


DATA ANALYTICS REFERENCE DOCUMENT

Document Title:52960 - Multi-Paradigm Programming
Document No.:1569071117
Author(s):Gerhard van der Linde, Rita Raher
Contributor(s):

REVISION HISTORY


Revision


Details of Modification(s)

Reason for modification

Date

By
0 Draft releaseDocument description here 2019/09/21 13:05 Gerhard van der Linde

52960 - Multi-Paradigm Programming

Goals

What is a Programming Paradigm?

MIPS Assembly

LUI R1, #1
LUI R2, #2
DADD R3, R1, R2

C or Java

(In fact this is syntactically valid in a lot of languages)

x = 1 + 2;

Abstraction

Examples of Abstraction

What is state?

given point in the program's execution, is called the program's state.

var total = 0;
var a = 1;
var b = 5;
total = a + b
print total;

Various Programming Paradigms

We shall have a brief look at each of these….

Sources

Week 3 - Imperative: Procedural

Goals of this session

Goals

Imperative Programming

Imperative I

Imperative II

Imperative III

Very General Structure First do this and next do that, then repeat this 10 times, then finish

Imperative IV

Imperative V

Listing 1: Very Simple Function in Python

def my_function():
   print("Hello from a function")
 
my_function()

Imperative VI

Listing 2: Slightly less simple Function in Python

def print_list(food):
   for x in food:
     print(x)
 
fruits = ["apple", "banana", "cherry"]
 
print_list(fruits)

Imperative VII

Listing 3: C Language Example (Procedural)

#print numbers from 1 to 10 
# include <stdio.h>
 
int main(){
   int i;
   for (i=1; i<11; ++i)
   {
   printf("%d ", i);
   }
   return 0;
}

Listing 3: Python Language Example (Procedural)

def myFunction():
   a = 0
   for a in range(0, 10):
      a += 1 # Same as a = a + 1 
      print (a, sep=' ', end=' ', flush=True)
 
 
myFunction()

Imperative VIII

Listing 4: Imperative with go-to

result = []
i = 0
start:
  numPeople = length(people)
  if i >= numPeople goto finished
  p = people[i]
  nameLength = length(p.name)
  if nameLength <= 5 goto nextOne
  upperName = toUpper(p.name)
  addToList(result, upperName)
nextOne:
  i = i + 1
  goto start
finished:
  return sort(result)

Imperative IX

Imperative X

Sources

Week 3 - The C Programming language

The C programming Language

The C programming Language I

The C programming Language II

Listing 1: Assembly Code for Hello World

global _main
extern _printf

section .text
_main:
  push message
  call _printf
  add esp, 4
  ret
message:
  db ’Hello, World!’, 10, 0

The C programming Language III

The C programming Language IV

Listing 2: Hello World in Standards Compliant C

#include <stdio.h>
int main(void)
{
   printf("hello, world\n");
}

Listing 2: Hello World in Standards Compliant python

def helloworld():
  print("Hello, world")
 
helloworld()  

The C programming Language V

The C programming Language VI

Write a C program to print your name, date of birth. and mobile number

#include <stdio.h>
int main(void)
{
  printf("Name: Dominic Carr\n");
  printf("DOB: June 12th, 1920\n");
  printf("086-1910000\n");
}

Write a python program to print your name, date of birth. and mobile number

def personinfo():
  print("Name: Dominic Carr")
  print("DOB: June 12th, 1920")
  print("086-1910000")
 
personinfo()

The C programming Language VII

Write a C program to print a block F using hash (#), where the F has a height of six characters and width of five and four characters

#include <stdio.h>
int main()
{
  printf("######\n");
  printf("#\n");
  printf("#\n");
  printf("#####\n");
  printf("#\n");
  printf("#\n");
  printf("#\n");
}

Python

def fpattern():
    print("######")
    print("#")
    print("#")
    print("#####")
    print("#")
    print("#")
    print("#")
 
fpattern()

Listing 3: Another Answer this time with a function

#include <stdio.h>
void print(int times, char a)
{
   for(int i = 0; i< times; i++)
   {
      printf("%c", a);
    }
    printf("\n");
}
int main()
{
   print(6,'#');
   print(1,'#');
   print(1,'#');
   print(5,'#');
   print(1,'#');
   print(1,'#');
}

python

def fpattern(n):
    for i in range(n):
        print("#", end='', flush=True)
    print(" ")
 
fpattern(5)
fpattern(1)
fpattern(1)
fpattern(5)
fpattern(1)
fpattern(1)

The C programming Language X

Write a C program to compute the sum of the two given integer values. If the two values are the same, then return triple their sum.

#include <stdio.h>
int sum(int a, int b)
{
   if (a==b)
   {
      return (a+b)*3;
    } else {
      return (a+b);
    }
}
 
int main()
{
   int res = sum(1,2);
   printf("Result is %d\n", res);
   res = sum(3,3);
   printf("Result is %d\n", res);
}

Python

def sumUp(a, b):
    if(a==b):
        return(a+b)*3
    else:
        return(a+b)
 
result = sumUp(1,2)   
print("Result is", result)
 
result = sumUp(3,3)  
print("Result is", result) 

Structs I

Listing 4: C Example of representing a Person

#include <stdio.h>
struct person
{
  int age;
  float weight;
};
 
int main()
{
   struct person *personPtr, person1;
   personPtr = &person1;
   printf("Enter age: ");
   scanf("%d", &personPtr->age);
   printf("Enter weight: ");
   scanf("%f", &personPtr->weight);
   printf("Age: %d\n", personPtr->age);
   return 0;
 
}

Structs III

C vs Python

Installing C on Windows

Online C compiler

https://www.onlinegdb.com/online_c_compiler and Compile our C code online!

C Practice Questions I

We will take a look at some of the “elementary” questions @ https://adriann.github.io/programming_problems.html Other

1.c

#include <stdio.h>
 
int main()
{
	printf("Hello, World\n");
	return 0;
}

1.py

print("Hello World")

2.c

#include <stdio.h>
 
int main()
{
	char name[20];
 
	printf("What is your name?");
 
	fgets(name,20,stdin);
 
	printf("Hello %s", name);
 
	return 0;
}

2.py

name = raw_input("What is your name?")
 
print("Hello %s, How are you?" %(name))

3.c

#include <stdio.h>
#include <string.h>
 
int main()
{
	char* name;
 
	printf("What is your name?");
 
	gets(name);
 
	if ((strcmp(name,"Alice")==0) || (strcmp(name,"Bob")==0))
	{
		printf("Hello %s\n", name);	
	} else 
	{
		printf("Hello lowly peasant!\n");
	}
 
	return 0;
}

3.py

name = raw_input("What is your name?")
 
if (name=="Bob") or (name=="Alice"):
    print("Hello %s, How are you?" %(name))
else:
    print("Hello lowly peasant!")

4.c

#include <stdio.h>
#include <string.h>
 
int main()
{
	int n;
	int sum = 0;
 
	printf("Please enter a Number: ");
	scanf("%d", &n);
 
	for(int i = 1; i<=n; i++)
	{
		sum += i;
	}
 
	printf("The sum of 1 to %d, was %d\n", n, sum);
 
	return 0;
}

4.py

n = input("Enter a number: ")
 
sum = 0
 
for i in range(1,n+1):
    sum = sum + i
 
print("The sum of 1 to %d, was %d" % (n, sum))

5.c

#include <stdio.h>
#include <string.h>
 
int main()
{
	int n;
	int sum = 0;
 
	printf("Please enter a Number: ");
	scanf("%d", &n);
 
	for(int i = 1; i<=n; i++)
	{
		if (((i%3)==0) || ((i%5)==0)) 
		{
			sum += i;
		}
	}
 
	printf("The sum of 1 to %d, was %d\n", n, sum);
 
	return 0;
}

5.py

n = input("Enter a number: ")
 
sum = 0
 
for i in range(1,n+1):
    if ((i % 3)==0) or ((1 % 5)==0):
        print i
        sum = sum + i
 
print("The sum of 1 to %d, was %d" % (n, sum))

6.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
int main()
{
	int n, sum = 0;
	int product = 1;
	char* choice = (char*) malloc(10 * sizeof(char));
 
	printf("Please enter a Number: ");
	scanf("%d", &n);
	printf("Do you want to do product or sum?");
	scanf("%s", choice);
 
	if (strcmp(choice, "product")==0)
	{
		for(int i = 1; i<=n; i++)
		{
			product *= i;
		}
 
		printf("The product of 1 to %d, was %d\n", n, product);
 
	} else if (strcmp(choice, "sum")==0)
	{
		for(int i = 1; i<=n; i++)
		{
			sum += i;
		}
 
		printf("The sum of 1 to %d, was %d\n", n, sum);
 
	}
	return 0;
}

6.py

n = input("Enter a number: ")
kind = raw_input("Do you want to do sum or product? ")
 
sum = 0
product = 1
 
if (kind == "sum"):
    for i in range(1,n+1):
        sum = sum + i
    print("The sum of 1 to %d, was %d" % (n, sum))
elif (kind == "product"):
    for i in range(1,n+1):
        product = product * i
    print("The product of 1 to %d, was %d" % (n, product))
else:
    print("I did not understand your request")

C Practice Questions II

Questions:

  1. Write a C program to get the absolute difference between n and 51. If n is greater than 51 return triple the absolute difference.
  2. Write a C program to check two given integers, and return true if one of them is 30 or if their sum is 30.
  3. Write a C program to compute the sum of the two given integers. If the sum is in the range 10..20 inclusive return 30
  4. Write a C program that accept two integers and return true if either one is 5 or their sum or difference is 5.
  5. Write a C program to check if y is greater than x, and z is greater than y from three given integers x,y,z
  6. Write a C program to check if two or more non-negative given integers have the same rightmost digit.

Abs Diff

abs_diff.c
  1. // Write a C program to get the absolute difference between n and 51.
  2. // If n is greater than 51 return triple the absolute difference.
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7.  
  8. int main()
  9. {
  10. char* choice = (char*) malloc(10 * sizeof(char));
  11. int n,val;
  12.  
  13. printf("Please enter a Number: ");
  14. scanf("%d", &n);
  15. printf("Number entered is : %d\n", n);
  16. if (n>51){
  17. val=(abs(n-51))*3;
  18. }
  19. else {
  20. val=(abs(n-51));
  21. }
  22. printf("result: %d\n",val);
  23. return val;
  24. }

Sum of integers

two_integers.c
  1. // Write a C program to check two given integers, and return
  2. // true if one of them is 30 or if their sum is 30
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <stdbool.h>
  8.  
  9. int main()
  10. {
  11. char* choice = (char*) malloc(10 * sizeof(char));
  12. int n1,n2,val;
  13.  
  14.  
  15. printf("Please enter first Number: ");
  16. scanf("%d", &n1);
  17. printf("Please enter second Number: ");
  18. scanf("%d", &n2);
  19.  
  20. printf("Numbers entered is : %d and %d \n", n1,n2);
  21. if (n1==30 || n2==30 ||n1+n2==30){
  22. val=true;
  23. }
  24. else {
  25. val=false;
  26. }
  27. printf("val is: %d\n", val);
  28. if(val==1){
  29. printf("Either values or sum of both equils 30, therefore....");
  30. printf("result: %s\n","TRUE");
  31. }
  32. else {
  33. printf("Neither values or the sum of both equils 30, therefore....");
  34. printf("result: %s\n","FALSE");
  35. }
  36. return val;
  37. }

Sources

Week 4 - Shop in C

c code

shop.c
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. struct Product {
  6. char* name;
  7. double price;
  8. };
  9.  
  10. struct ProductStock {
  11. struct Product product;
  12. int quantity;
  13. };
  14.  
  15. struct Shop {
  16. double cash;
  17. struct ProductStock stock[20];
  18. int index;
  19. };
  20.  
  21. struct Customer {
  22. char* name;
  23. double budget;
  24. struct ProductStock shoppingList[10];
  25. int index;
  26. };
  27.  
  28. void printProduct(struct Product p)
  29. {
  30. printf("PRODUCT NAME: %s \nPRODUCT PRICE: %.2f\n", p.name, p.price);
  31. printf("-------------\n");
  32. }
  33.  
  34. void printCustomer(struct Customer c)
  35. {
  36. printf("CUSTOMER NAME: %s \nCUSTOMER BUDGET: %.2f\n", c.name, c.budget);
  37. printf("-------------\n");
  38. for(int i = 0; i < c.index; i++)
  39. {
  40. printProduct(c.shoppingList[i].product);
  41. printf("%s ORDERS %d OF ABOVE PRODUCT\n", c.name, c.shoppingList[i].quantity);
  42. double cost = c.shoppingList[i].quantity * c.shoppingList[i].product.price;
  43. printf("The cost to %s will be €%.2f\n", c.name, cost);
  44. }
  45. }
  46.  
  47. struct Shop createAndStockShop()
  48. {
  49. struct Shop shop = { 200 };
  50. FILE * fp;
  51. char * line = NULL;
  52. size_t len = 0;
  53. ssize_t read;
  54.  
  55. fp = fopen("stock.csv", "r");
  56. if (fp == NULL)
  57. exit(EXIT_FAILURE);
  58.  
  59. while ((read = getline(&line, &len, fp)) != -1) {
  60. // printf("Retrieved line of length %zu:\n", read);
  61. // printf("%s IS A LINE", line);
  62. char *n = strtok(line, ",");
  63. char *p = strtok(NULL, ",");
  64. char *q = strtok(NULL, ",");
  65. // create variables from the strings to populate the structures
  66. int quantity = atoi(q);
  67. double price = atof(p);
  68. // create a variable to make a permanent copy of the string that is pointed to only in n
  69. char *name = malloc(sizeof(char) * 50);
  70. strcpy(name, n);
  71. // instanssiate the first structure to go into the second structure and insert the values in
  72. struct Product product = { name, price };
  73. struct ProductStock stockItem = { product, quantity };
  74. // as pointed out in the video, a lot happens in this line, see the detailed description below
  75. shop.stock[shop.index++] = stockItem;
  76. // printf("NAME OF PRODUCT %s PRICE %.2f QUANTITY %d\n", name, price, quantity);
  77. }
  78.  
  79. return shop;
  80. }
  81.  
  82. void printShop(struct Shop s)
  83. {
  84. printf("Shop has %.2f in cash\n", s.cash);
  85. for (int i = 0; i < s.index; i++)
  86. {
  87. printProduct(s.stock[i].product);
  88. printf("The shop has %d of the above\n", s.stock[i].quantity);
  89. }
  90. }
  91.  
  92. int main(void)
  93. {
  94. // struct Customer dominic = { "Dominic", 100.0 };
  95. //
  96. // struct Product coke = { "Can Coke", 1.10 };
  97. // struct Product bread = { "Bread", 0.7 };
  98. // // printProduct(coke);
  99. //
  100. // struct ProductStock cokeStock = { coke, 20 };
  101. // struct ProductStock breadStock = { bread, 2 };
  102. //
  103. // dominic.shoppingList[dominic.index++] = cokeStock;
  104. // dominic.shoppingList[dominic.index++] = breadStock;
  105. //
  106. // printCustomer(dominic);
  107.  
  108. struct Shop shop = createAndStockShop();
  109. printShop(shop);
  110.  
  111. // printf("The shop has %d of the product %s\n", cokeStock.quantity, cokeStock.product.name);
  112.  
  113. return 0;
  114. }

This line of code on line 75 is packed with functionality and important to understand in order to reproduce the functionality for the assignments.

shop.stock[shop.index++] = stockItem;

You need to refer to the Shop structure defined on line 15 in the c code sample above. This structure is then instantiated on line 49 and named shop. This structure shop contains another structure ProducStock named stock and an array of 20 of this is defined.

So in order to loop through this array the index is created that needs to be maintained and used to fill the right indexed positions.

So in summary shop contains three named values, cash, stock and indextherefore lines 72 and 73 creates the new structured values that is required to populate into the stock variable.

So in the line shop.stock[shop.index++] = stockItem; we insert into shop.stock at indexed position shop.index the new value created in lines 72 and 73 stockItem and while doing this incrementing shop.index by one by appending the ++ in the line of code.

stock csv file

stock.csv
Coke Can, 1.10, 100
Bread, 0.7, 30
Spaghetti, 1.20, 100
Tomato Sauce, 0.80, 100
Big Bags, 2.50, 4

Week 6 - Object Oriented Programming

1. Goals of this Session

2. Object-Oriented

Goals of this Session

Paradigms I

Recall

Object-Oriented

Object-Oriented I

Object-Oriented II

Object-Oriented III

Listing 1: Person Class in Java

public final class Person {
  private final String name;
  private final int age;
 
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
   }
   public String toString() {
     return name + " " + info;
   }
   public static void main(String[] args) {
     Person a = new Person("Alice", 12);
     Person b = new Person("John", 34);
   }
}

Object-Oriented IV

Listing 2: Person Class in Ruby

class Person
    def initialize(name, age)
       @name = name
       @age = age
    end
 
    def name
    # labelname is only in scope within the name
        method
    labelname = "Fname:"
    return labelname + @name
    end
end

Object-Oriented V

Object-Oriented VI

Listing 3: C Example of representing a Person

#include <stdio.h>
struct person
{
   int age;
   float weight;
};
int main()
{
   struct person *personPtr, person1;
   personPtr = &person1;
   printf("Enter age: ");
   scanf("%d", &personPtr->age);
   printf("Enter weight: ");
   scanf("%f", &personPtr->weight);
   printf("Age: %d\n", personPtr->age);
   return 0;
}

Object-Oriented VII

Object-Oriented VIII

Message Passing

    receiver_object.method_name(argument1, argument2, ...)

Object-Oriented IX

Message Passing

math_solver.add(12, 30)

Object-Oriented X

Java: Impure

Object-Oriented XI

Java: Impure

Object-Oriented XII

Inheritence

class Mammal
  def breathe
    puts "inhale and exhale"
  end
end
 
class Lion < Mammal
  def speak
    puts "Roar!!!"
  end
end

Object-Oriented XIII

Object-Oriented XIV

Object-Oriented XV

Object-Oriented XVI

Object-Oriented XVII

Object-Oriented XVIII

class Mammal
  def breathe
   puts "inhale and exhale"
  end
end
 
class Lion < Mammal
......
 
end
 
class Monkey < Mammal
......
end

Object-Oriented XIX

Object-Oriented X

Interface

“an interface is a shared boundary across which two or more separate components of a computer system exchange information”

Object-Oriented XXI

Object-Oriented XXII

Object-Oriented XXIII

Sources

https://www.computerhope.com/jargon/i/imp-programming.htm

https://en.wikipedia.org/wiki/Abstraction_(computer_science)

Java

  1. Goals of this Session
  2. 2 The Java Language
    1. Hello World in Java
    2. Inheritance in Java
    3. OOP Example in Java
  3. 3 Comparison with Python
  4. 4 Java Virtual Machine
  5. 5 Sources

Goals of this Session

The Java Language

Java I

“Write once, run anywhere” - Java Language Tagline

Java II

Java III

Listing 1: Hello Java World!

public class HelloWorldApp {
  public static void main(String[] args) {
    System.out.println("Hello World!"); // Prints the string
to the console.
  }
}

Java IV

Java V

Java VI

class subClass extends superClass
{
//methods and fields
}

Java VII

Listing 2: Person Object in Java

public class Person {
   private int age;
   private String name;
 
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   }
 
   public void setAge(int age){
      if (!(age <= 0 || age >= 110)){
      this.age = age;
      }
   }

Example I

public class Person {
   private int age;
   private String name;
 
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   }
 
   public String toString(){
       return "Name:" + this.name + " Age: " + this.age;
   }
 
   public static void main(String[] args) {
       Person a = new Person("John", 23);
       Person b = new Person("Paul", 51);
       System.out.println(a);
       System.out.println(b);
 
   }
 
 
}

Java IX

How to run a java file on a mac in terminal?

Compiling and Running

$ javac Person.java

$ java Person

output:

# Name:John Age: 23

# Name:Paul Age: 51

Java X

Example II

Person.java
public class Person {
   private String name;
   private int age;
 
   public Person(String n, int a){
      this.name = n;
      this.age = a;
   }
 
   public String toString(){
       return "Name:" + this.name + " Age: " + this.age;
   }
 
   public void setAge(int n){
       if (n < 0){
           // this line is a comment, we want to finish method and not modify the age
           return;
       }
       this.age = n;
 
    }
}
PersonAppRunner.java
public class PersonAppRunner{
 
    public static void main(String[] args) {
        Person a = new Person("John", 23);
        Person b = new Person("Paul", 51);
        System.out.println(a);
        //a.age = -1;
        a.setAge(40);
        System.out.println(a);
        System.out.println(b);
 
    }
}
Student.java
//inheritance example
public class Student extends Person{
 
    private String[] classes;
 
    public Student(String n, int a, String[] c){
        super(n, a);
        this.classes = c;
    }
 
    public String toString(){
        String repr = super.toString() + "\nCLASSES: \n";
        for(int i=0; i<classes.length; i++){
            repr += classes[i] + "\n";
        }
        return repr;
    }
 
    public static void main(String[] args){
        String[] classes = new String[] {"Introduction to Maths", "Management for Computing", "Programming 1"};
        Student s = new Student("Pramod", 58, classes);
        s.setAge(59);
        System.out.println(s);
    }
 
 
}

Java XI

Java XII

Paul is 25

* It looks like the student prints out just like a Person as it calls the superclass toString method

Java XIII

Java XIV

Comparison with Python

Python OOP I

person.py
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
 
p1 = Person("John", 36)
 
print(p1.name)
print(p1.age)

Python OOP II

Java Virtual Machine

JVM I

JVM II

Sources

https://www.computerhope.com/jargon/i/imp-programming.htm https://en.wikipedia.org/wiki/Abstraction_(computer_science) https://www.guru99.com/java-class-inheritance.html https://www.w3schools.com/python/python_classes.asp

Declarative Programming

Goals

Declarative programming

Programming by specifying the result you want, not how you get it.

SELECT UPPER(name)
FROM people
WHERE LENGTH(name) > 5
ORDER BY name

Declarative II

SELECT * FROM Worker ORDER BY FIRST_NAME ASC;

Declarative III

SQL

Popularity of SQL

Companies using SQL

Popularity of SQL

SQL Syntax

SQL Language Elements

Standard SQL

SELECT OrderID, Quantity, 
CASE WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quanity is under 30"
END AS QuantityText
FROM OrderDetails;

Comparison with C

Imagine the schema looks like:

personId INTEGER PRIMARY KEY, name VARCHAR(20), sex CHAR(1), birthday DATE, placeOfBrith VARCHAR(20);

How would we find teh oldest person in the table?

SELECT * FROM people
 ORDER BYY birthday ASC
 LIMIT 1;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
struct Person{
   char* name;
   char sex;
   int age;
   char* placeOfBirth;
}
 
int main(void){
   struct Person a = {"Anthony Stynes","M", 12, "New York"};
   struct Person b = {"Bertie Corr", "M", 1000, "Boston"};
   struct Person c = {"John Quin", "M", 33, "'Murica"};  
}
 
struct Person arr[] = {a, b, c};
int maxAge = -1;
int index = 0;
 
for(int 1=0;i<3;i++){
   if(int i=0;i<3; i++){
       maxAge=arr[i].age;
       index=i;
    }
  }
printf("%s is oldest\n", arr[index].name);
 
return 0;
}

What's the most complex SQL query you ever wrote?

Greg Kemnitz, Postgres internals, embedded device db internals MySQL user level

“I wrote a reporting query once that was 700 lines long and visited 27 different tables in lookups or joins. It didn't do any fancy stuff - just straigh whereclause predicates and joiing - but it was pretty gnarly and took 3 days to compose, debug and tune

Bill Karwin, author of “SQL Antipatterns: Avoiding the pitfalls of database programming”

“One of the fun, complex sql queries I wrote was for a demo I did during a talk at OSCON 2006, SQL Outer Joins for Fun and Profit. It was a query that solved Sudoku puzzles”

Level of Abstraction

Make

CFLAGS ?= -g
 
all:helloworld
 
helloworld: helloworld.o
   # Commands start with TAB not spaces
   $(CC) $(LDFLAGS) -o $@ $^
 
helloworld.o : helloworld.c
   $(CC) $(CFLAGS) -c -o $@ $<
 
clean: FRC
   rm -f helloworld helloworld.o
 
#This pseudo target causes all targets that depend on FRC 
# to be remade even in case a file with the name of the target exists
# this works with any make implementation under the assumption that
 
# there is no file FRC in the current directory
FRC:   

Functional Programming

Functional programming is a subset of declarative programming.

Covered in this section:

  1. Goals of this Session
  2. Mathematical Functions
  3. Functional Programming
  4. Referential Transparency
    • Pure Functions
    • Impure Functions
  5. Recursion
    • The Fibonacci Sequence
    • Factorial
    • Recursion Exercises
  6. Sources

Goals

Mathematical functions

Functional Programming

Functional Programming II

Functional programming languages are declarative, meaning that a computation’s logic is expressed without describing its control flow Some languages support functional programming constructs without being purely functional.

Referential Transparency

Referential transparency is generally defined as the fact that an expression, in a program, may be replaced by its value (or anything having the same value) without changing the result of the program.

In other words we can replace any called to a pure function with it’s result as the function result depends only on it’s inputs.

def add(a, b):
   return a + b
 
def mult(a, b):
   return a * b
 
x = add(2, mult(3, 4))
 
print x

Referential Transparency I

call_counter = 0
 
def add(a, b):
  return a + b
 
def mult(a, b):
   global call_counter
   call_counter = call_counter + 1
   return a * b
 
x = add(2, mult(3, 4))
 
print x

Referential Transparency II

Definition

Impure Functions I

Impure Functions II

class Person:
  def __init__(self, name, surname, age):
    self.name = name
    self.surname = surname
    self.age = age
 
  def can_vote(self, voting_age):
    if (self.age > voting_age):
       return True
    else:
       return False
 
person = Person("Jane",
                 "Doe",
                  12)
 
print person.can_vote(18)
 
person.age = 19
 
print person.can_vote(18)
#Consider the following addition to the person class:
 
 
def same(self,p):
  if (p.name == self.name):
     p.name = "side effect"
     return True
   else:
     p.age = 101
     return False
 
#If we have
person = Person(
       "Jane",
       "Doe",
       12
)
 
john = Person(
       "John",
       "Joe",
        59
)
 
#and we perform
 
print person.same(john)
 
print john.age

are there side effects?

Consider this example:

limit = 100
 
def calculatebonus(num_sales):
   return 0.10 * num_sales if num_sales > limit else 0
 
def calculatebonus2(numSales):
   return 0.10 * num_sales if num_sales > 100 else 0
 
print(calculatebonus2(174))      

Of the two functions, which is pure and which is not pure?

The answer is option one is impure because limit exists outside the function and affects the outcome in unpredictable ways.

Recursion

Definition

“Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration). The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science”

Mostly this means that the programming language allows a method to invoke itself.

The Fibonacci Sequence I

Definition

“In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones”

0, 1, 1, 2, 3, 5, 8, 13, 21, 34…

The Fibonacci Sequence II

The Fibonacci Sequence III

Listing 1: Algorithm to determine the nth fibonacci number

def fib(n):
   if (n==1):
      return 0
   a = 0
   b = 1
   for i in range(2,n):
     c = a + b
     a = b
     b = c
   return b
 
for i in range(1,10):
   print fib(i)
 

This is an iterative solution to calculating the nth Fibonacci number, put simply this means that it is a method / function which loops to repeat some part of the code. A recursive method is one which calls itself to repeat the code.

The Fibonacci Sequence IV

This is an iterative solution to calculating the nth Fibonacci number, put simply this means that it is a method / function which loops to repeat some part of the code. A recursive method is one which calls itself to repeat the code.

Listing 2: Output of the program

0
1
1
2
3
5
8
13
21

The Fibonacci Sequence V

So do we achieve a recursive solution for this problem?

The Fibonacci Sequence VI

File “1.py”, line 2, in fib

return fib(n-1) + fib(n-2)

RuntimeError: maximum recursion depth exceeded

The Fibonacci Sequence VII

For the Fibonacci we can define three conditions:

Listing 3: Recursive implementation of fib

def fib(n):
   if (n==1 or n==0):
      return n
   return fib(n-1) + fib(n-2)
 
for i in range(1,10):
   print fib(i)
 

The Fibonacci Sequence VIII

What we have done in this specific case can be applied to all recursive algorithms. As all such algorithms must have the following properties to operate.

Factorial I

Definition

“In mathematics, the factorial of a non-negative integer n, denoted by n!,is the product of all positive integers less than or equal to n.”

5! = 5 × 4 × 3 × 2 × 1 = 120

Factorial II

Listing 4: Iterative calculation of the factorial of n

def factorial(n):
   factorial = 1;
   for i in range(2,n+1):
     factorial = factorial * i
    return factorial
 
print factorial(5)

How to do it recursively?

Factorial III

Listing 5: Recursive solution to factorial of N)

def factorial(n):
if (n == 0):
return 1
return n * factorial(n-1);
print factorial(5)

Why do we not need a condition for 1 as a special case?

Tasks I

Recursive solutions to the following:

Calculate Powers

def pow(num, power):
    if (power == 1):
        return num
    return num * pow(num, power-1)
 
if __name__ == '__main__':
  v=pow(3,4)
  print('{}'.format(v))

Palindrome

def palindrome(word):
    length = len(word)
    #print("length was %d" % length)
    if (length <= 1):
        return True
    #print( "comparing %s with %s result is %r" % (word[0], word[length-1], (word[0] == word[length-1])))
    return (word[0] == word[length-1]) and palindrome(word[1:length-1])
 
if __name__ == '__main__':
  print('{}'.format(palindrome('madam')))

Reverse

def reverse(word):
    length = len(word)
    if (length <= 1):
        return word
    return word[length-1] + reverse(word[:length-1])
 
if __name__ == '__main__':
    print('{}'.format(reverse('cinimod')))
 

Iterable

This example in Python 2.7, the code below does not work for 3.7.

class StringIterator:
    def __init__(self, string):
        self.string = string
        self.index = 0
        self.length = len(string)
 
    def __iter__(self):
        return self
 
    def next(self):
        if self.index >= self.length:
            raise StopIteration
        else:
            self.index+=1
        return self.string[self.index-1]
 
print filter((lambda x: x != "i"), StringIterator("dominic"))
 

Lambdas and map

x = [1,2,3,4,5,6]
 
square = lambda x: x * x
 
print (square(2))
 
result = list(map(square, x))
 
print (result)
 
print (list(map(square, result)))

Filter and Reduce

import functools
 
print(functools.reduce((lambda x, y: x + y), [1,2,3,4,5,6]))
# 21
 
print(list(filter((lambda x: x > 3), [1,2,3,4,5,6])))
#[4, 5, 6]