String str = "Hello World";
void print_string(){
printf (str);
}
int update_counter (int counter){
counter ++;
return counter;
}
int student_count = 0;
Student update_record (Student stu, int roll){
stu.roll_no = roll;
student_count ++;
}
class Student {
int roll;
String name;
}
int stu_count = 0;
void updateRecord (Student stu, int roll){
String name = "";
cin >> name;
cout << "Name " << name << "Roll:" << roll;
stu.roll = roll;
stu.name = name;
stu_count ++;
}
void updateRecord (Student stu, int roll){
String name = "";
//side-effect
cin >> name;
//side-effect
cout << "Name: " << name << "Roll: " << roll;
stu.roll = roll;
stu.name = name;
//side-effect
stu_count ++;
}
class Student {
int roll;
String name;
}
int stu_count = 0; // Global variable
!! for pure functional !!
int i = 5;
int j = 6;
int s = sum(i, j); // 11
i++;
s = sum(i, j); // 12
No \(i\)++ in functional programming.
int i = 5;
int j = 6;
int s = sum(i, j); // 11
int i = i + 1;
int s = sum(i, j); // 12
fun increment(i){
return i+1;
}
fun main(){
int i = 5;
int j = increment(i); //6
}
fun increment(i){
return i+2;
}
1
2
fun increment(i){
print("received value is %i");
return i+1;
}
fun main(){
int i = 5;
int j = increment(i); //6
}
3
A function which can be used as a variable.
fun sum (a, b) {
return (a+b)
}
var a = sum;
a (5,6); //11
Assignment
fun operate (operation, a, b){
return operation (a, b);
}
operate (sum, 5, 6); //11
Passing as argument
Returning as a result
fun select_operator (index){
fun sum (a,b) {return (a+b);}
fun diff (a,b){return (a-b);}
if(index == 1){
return sum;
}else{
return diff;
}
}
fun main(){
cin >> index;
fun a = select_operator(index);
a(5,6);
//do something
a(6,7);
}
A function which takes or returns another function
fun select_operator (index){
if(index == 1){
return (fun (a,b) => (a+b))
}else{
return (fun (a,b) => (a-b))
}
}
Alternate representation with lambda operator
module List {
type t
fun add (list:t, newitem) {
return (list + newitem);
}
fun remove (list:t, item){
return (list - item);
}
}
type Option =
| Some x
| None
int i = None;
operate (i);
int i = Some (5);
operate (i);
Memoization...kind of !!!
result
f
f
f
3
4
4
3
//Normal Evaluation
result = f(f(a,b), f(a,b));
= f(f(3,4), f(a,b))
= f(7, f(a,b))
= f(7, f(3,4))
= f(7, 7)
= 14
f = sum;
a=3;
b=4;
result
f
f
3
4
//Lazy Evaluation
result = f(f(a,b), f(a,b));
= f(f(3,4), f(a,b))
= f(7, 7)
= 14
f = sum;
a=3;
b=4;
func evaluate (a, b){
print (values are %a and %b);
return a+b;
}
func prod(a,b){
return a*b
}
func run (){
return ( prod (evaluate (3,4), evaluate (3,4)) );
}
//output
values are 3 and 4
values are 3 and 4
49
Lazy func evaluate (a, b){
print (values are %a and %b);
return a+b;
}
func prod(a,b){
return a*b
}
func run (){
return ( prod (evaluate (3,4), evaluate (3,4)) );
}
//output
values are 3 and 4
49
OOP
FP
A more thorough testing would have avoided many such failures, but is it that easy???
Testing becomes difficult when the program has :
\(^*\)Some guy getting paid by FP people