Presentation is loading. Please wait.

Presentation is loading. Please wait.

Nov 2005 SDP-MSc Slide 1 Section 10 Functional Programming in C#

Similar presentations


Presentation on theme: "Nov 2005 SDP-MSc Slide 1 Section 10 Functional Programming in C#"— Presentation transcript:

1 Nov 2005 SDP-MSc Slide 1 Section 10 Functional Programming in C#

2 Nov 2005 SDP-MSc Slide 2 References http://www-compsci.swan.ac.uk/~csetzer/articles/javafunctional.pdf Java as a Functional Programming Language - A.Setzer http://www.cs.hmc.edu/claremont/keller/webBook/ch07/sec23.html Higher-Order Functions as Objects

3 Nov 2005 SDP-MSc Slide 3 Principles Reviewed 3 No Side effects No variable assignment A Function has no effect other than calculating its value

4 Nov 2005 SDP-MSc Slide 4 Key Features- Functional Programs 4 Higher Order Functions Lazy Evaluation Currying Lambda Expressions List Processing

5 Nov 2005 SDP-MSc Slide 5 Functional Programs 5 Program consists only of Functions Main program is a function, receives input as parameters May in turn be defined as other functions

6 Nov 2005 SDP-MSc Slide 6 - No side effects 6 class Fun2 { public static int res; // global variable public static void sum(int a, int b){ res= a+b;} // side effect public static void Main(string[] args) { int x=Convert.ToInt32(args[0]); int y=Convert.ToInt32(args[1]); sum(x,y); Console.WriteLine("Sum of values:{0}", res); }

7 Nov 2005 SDP-MSc Slide 7 Function result only depends on input parameters Always returns the same result, whenever called Order of function calls irrelevant: f(x)=2*x + 1 => f(2)=5 always Functional Programming -

8 Nov 2005 SDP-MSc Slide 8 No Side-effects - Summary No global variables No variable assignment Function just calculates a value based on input parameters Next: Another counter example

9 Nov 2005 SDP-MSc Slide 9 class Fact1 { public static int factorial(int n){ int res=1; for (int i=1;i<=n;i++) res*=i; // var assignment return res;} public static void Main(string[] args) { int x=Convert.ToInt32(args[0]); Console.WriteLine("Factorial= {0}", factorial(x)); }

10 Nov 2005 SDP-MSc Slide 10

11 Nov 2005 SDP-MSc Slide 11 Recursion Most Functional Programming Languages use recursion - avoids variable assignment - facilitates Lazy Evaluation

12 Nov 2005 SDP-MSc Slide 12 class Fact2 { public static int factorial(int n){ if (n==0) return 1; else return n * factorial(n-1); } public static void Main(string[] args) { int x=Convert.ToInt32(args[0]); Console.WriteLine("Factorial= {0}", factorial(x)); }

13 Nov 2005 SDP-MSc Slide 13 Functional Programming Two other key features - List Processing - Polymorphic Types

14 Nov 2005 SDP-MSc Slide 14 class Vec3{ public static int total(ArrayList vec){ int res=0; for(int i=0; i<vec.Count;i++) { res+= (int)vec[i]; } return res;} public static void Main() { ArrayList v=new ArrayList(); v.Add(1); v.Add(2); v.Add(3); Console.WriteLine("Sum of Elements: {0}", total(v));} }

15 Nov 2005 SDP-MSc Slide 15 Next Fuctional Version

16 Nov 2005 SDP-MSc Slide 16 class Vec4 {public static int convert(Object o){ return ((Integer)o).intValue();} public static int total(Vector vec,int first){ if (vec.isEmpty()) return 0; if (first==vec.size()-1) return convert(vec.elementAt(first)); else return convert(vec.elementAt(first)) + total(vec,first+1); }

17 Nov 2005 SDP-MSc Slide 17 : public static void main(String[] args) { Vector v=new Vector(); v.addElement(new Integer(Integer.parseInt(args[0]))); v.addElement(new Integer(Integer.parseInt(args[1]))); v.addElement(new Integer(Integer.parseInt(args[2]))); System.out.println("Sum of Elements: "+ total(v,0)); }

18 Nov 2005 SDP-MSc Slide 18 Now to search vector [3,4,5] for a value

19 Nov 2005 SDP-MSc Slide 19 Functional Programming -other key features Higher Order Functions Lazy Evaluation Currying Lambda expressions (Nameless functions) All of these depend on Higher Order Functions

20 Nov 2005 SDP-MSc Slide 20 Lazy Evaluation Normal Evaluation: mult (fac 3) (fac 4) Evaluate parameter first: mult 6 24 => 144 Lazy Evaluation - only evaluate (fac 3) etc when needed

21 Nov 2005 SDP-MSc Slide 21 Lazy Evaluation mult (fac 3) (fac 4) becomes (fac 3) * (fac 4) = 6 * 24 => 144 Lazy Evaluation - only evaluate (fac 3) etc when needed

22 Nov 2005 SDP-MSc Slide 22 Lazy Evaluation - C# Using ‘if’ statements in C# to implement ‘Lazy’ : if (x <10) return increment(x); else return 10;} :

23 Nov 2005 SDP-MSc Slide 23 Lazy Evaluation - Java Recursive Functions also facilitate Lazy Evaluation Factorial…

24 Nov 2005 SDP-MSc Slide 24 Lazy Evaluation - Java Ability to pass functions ‘unevaluated’ is central to ‘Lazy Evaluation’ I.e. Higher Order Functions

25 Nov 2005 SDP-MSc Slide 25 Higher Order Functions A Function which takes another function as parameter Function can also be returned as a result I.e Functions treated as Objects increment :: Int -> Int increment n = (n+1)

26 Nov 2005 SDP-MSc Slide 26 Higher Order Functions increment :: Int -> Int increment n = (n+1) map1 :: (a -> b) -> [a] -> [b] map1 f [] = [] map1 f (x:xs) = f x : map1 f xs > map1 increment [1,2,3,4] [2,3,4,5]

27 Nov 2005 SDP-MSc Slide 27 Higher Order Functions Two Methods in C# (1)Using interface and polymorphism: pass an Object which refers to a method (2) Using delegate type pass a reference to a function

28 Nov 2005 SDP-MSc Slide 28 Higher Order Functions In this section (1)Using interface and polymorphism for HOF: (2) Delegate type in general (3) Delegate type for HOF

29 Nov 2005 SDP-MSc Slide 29 Higher Order Functions in C# using interface using System; public interface OneArgFunction{ int apply(int x); } class Increment :OneArgFunction{ public int apply(int x){ return x+1;} } increment :: Int -> Int increment n = (n+1)

30 Nov 2005 SDP-MSc Slide 30 public class TestHOF1{ public static void map(OneArgFunction f, int[] a) {for (int i=0;i<a.Length;i++){ a[i]=f.apply(a[i]);} } public static void Main(string[] args){ int[] arr={3,4,5,6,7}; map(new Increment(),arr); for (int i=0; i<5;i++){ Console.WriteLine("["+arr[i]+"]");} Console.Read(); }}

31 Nov 2005 SDP-MSc Slide 31 Write a function which : - takes a function & list of Ints as paramemets - applies function to first & last element - return result as sum of these two wlaues >sum_fl increment [3,4,5,6] 11 i.e 4 + 7 sum_fl :: (Int -> Int) -> [Int] -> Int sum_fl f (x:xs) = f x + f (last xs) Now the Java Version -->

32 Nov 2005 SDP-MSc Slide 32 using System; public interface Operation{ int apply(int x); } class Increment :Operation{ public int apply(int x){ return x+1;}} :

33 Nov 2005 SDP-MSc Slide 33 : public class TestHOF4{ public static int sum_fl(Operation f, int[] a) { return f.apply(a[0])+ f.apply(a[a.Length-1]); } public static void Main(string[] args){ int[] arr={3,4,5,6,7}; int res=sum_fl(new Increment(),arr); Console.WriteLine("Sum of 1st & Last= {0}",res); Console.Read(); }}

34 Nov 2005 SDP-MSc Slide 34 Another Example Add.op(2,3) -> 5 apply_op (Add.op, [3,4,5,6,7]) -> 25

35 Nov 2005 SDP-MSc Slide 35 using System; using System.Collections; public interface Operation{ int op(int x, int y); } class Add : Operation{ public int op(int x,int y){ return x+y;}}:

36 Nov 2005 SDP-MSc Slide 36 : public class Ex1{ public static int apply_op(Operation f, int[] a) {int res=0; for (int i=0; i<a.Length;i++) {res = f.op(res,a[i]);} return res; }

37 Nov 2005 SDP-MSc Slide 37 : public static void Main(string[] args){ int [] arr={3,4,5,6,7}; int res=apply_op(new Add(), arr); Console.WriteLine("Sum of elements= "+res); Console.Read();} }

38 Nov 2005 SDP-MSc Slide 38 Exercise 1 Large implemements Validate -- inner class testval 8 returns false testval 11 returns true - values >= 10 test_list testval [2, 12, 8, 17, 9] returns false test_list testval [12, 13, 18, 17,19] returns true

39 Nov 2005 SDP-MSc Slide 39 Exercise 2 Bigger implements Validate-- inner class compare 8,9 returns false compare 9,8 returns true compare 9,9 returns false test_list compare [12, 8, 17, 9] 9 returns false test_list compare [12, 8, 17, 9] 7 returns true Create 2 versions: (a) Bigger as an Inner Class (b) Anonymous (nameless Inner Class)

40 Nov 2005 SDP-MSc Slide 40 Filter Example Small 8 returns true Small 11 returns false myfilter small, [2, 12, 8, 17, 9], 0 returns [2, 8, 9]

41 using System; using System.Collections; public interface Validate{ bool testval(int n); } class Small : Validate{ public bool testval(int n){ if (n<10) return true; else return false; }

42 public class HOFsmall1{ public static void myFilter(Validate f, ArrayList v, int index) { if (v.Count==0) return; if (index==v.Count) return; else {int el=(int)v[index]; if (f.testval(el)==false) { v.RemoveAt(index); myFilter(f,v,index);} else myFilter(f,v,index+1);} } :

43 public static void Main(string[] args){ ArrayList a=new ArrayList(); a.Add(2); a.Add(19); a.Add(9); a.Add(14); a.Add(9); a.Add(8); myFilter(new Small(),a,0); for (int i=0; i<a.Count;i++){ int val=(int)a[i]; Console.WriteLine("["+val+"]");} Console.Read(); }}

44 Nov 2005 SDP-MSc Slide 44 Another Filter Example greater 8 9 returns false greater 9 8 returns true greater 9 9 returns false myfilter greater, [2, 12, 4, 3, 9], 3, 0 returns [12, 4, 9]

45 Nov 2005 SDP-MSc Slide 45 using System; using System.Collections; public interface Condition{ bool test(int x,int y); } class Greater :Condition{ public bool test(int x,int y){ if (x>y) return true; else return false; }

46 Nov 2005 SDP-MSc Slide 46 public class HOFgreater1{ public static void myFilter(Condition f,ArrayList v, int val,int index) { if (v.Count==0) return; if (index==v.Count) return; else { int el=(int)v[index]; if (f.test(el,val)==false) { v.RemoveAt(index); myFilter(f,v,val,index);} else myFilter(f,v,val,index+1); }

47 Nov 2005 SDP-MSc Slide 47 public static void Main(string[] args){ ArrayList a=new ArrayList(); a.Add(7); a.Add(19); a.Add(9); a.Add(6); a.Add(14); a.Add(24); myFilter(new Greater(),a,8,0); for (int i=0; i<a.Count;i++){ int val=(int)a[i]; Console.WriteLine("["+val+"]");} Console.Read(); }}

48 Nov 2005 SDP-MSc Slide 48 Modify previous Filter Example in 2 ways equal 8 9 returns false equal 9 9 returns true filter_Out equal, [3, 12, 4, 3, 9], 3, 0 returns [12, 4, 9] Exercise 3

49 Nov 2005 SDP-MSc Slide 49 The delegate type Pointer to function

50 Nov 2005 SDP-MSc Slide 50 class GFrame4 :GFrame3 { protected Button b1=new Button(); public GFrame4():base(){ b1.Text= "Change Colour"; b1.SetBounds(100,180,90,23); b1.Click += new EventHandler(this.button1_Click); Controls.Add(b1); } private void button1_Click(object sender, EventArgs e){ brush.Color=Color.Yellow; this.Refresh();} } public class Test92{ public static void Main(string[] args){ Application.Run(new GFrame4());} }

51 Nov 2005 SDP-MSc Slide 51 First a Basic Example

52 Nov 2005 SDP-MSc Slide 52 using System; using System.Collections; public delegate void Operation(); // type definition public class Test{ public static void print(){ Console.WriteLine("Hello");} public static void Main(string[] args){ Operation o=new Operation(print); // delegate o(); Console.Read(); }}

53 Nov 2005 SDP-MSc Slide 53

54 Nov 2005 SDP-MSc Slide 54 public delegate void Operation(); public class Test{ public static void print1(){ Console.WriteLine("Hello");} public static void print2(){ Console.WriteLine("World");} public static void Main(string[] args){ Operation o=new Operation(print1); o+= new Operation(print2); o(); Console.Read(); }}

55 Nov 2005 SDP-MSc Slide 55 Now to Pass Pointers to Functions as Parameters

56 Nov 2005 SDP-MSc Slide 56 public delegate void Operation(); public class Test{ private int x=2; public void incr(){x++;} public void decr(){x--;} public void print(){ Console.WriteLine("Value={0}",x); } public void Action(Operation o){ o();} }

57 Nov 2005 SDP-MSc Slide 57 public class Test99{ public static void Main(string[] args){ Test t=new Test(); Operation o1=new Operation(t.incr); Operation o2=new Operation(t.print); t.Action(o1); t.Action(o2); Console.Read(); }}

58 Nov 2005 SDP-MSc Slide 58

59 Nov 2005 SDP-MSc Slide 59 public class Test99{ public static void Main(string[] args){ Test t=new Test(); Operation o1=new Operation(t.incr); o1 +=new Operation(t.print); t.Action(o1); Console.Read(); }} Alternative Test Function

60 Nov 2005 SDP-MSc Slide 60

61 Nov 2005 SDP-MSc Slide 61 public delegate void Operation(); public class Test{ private int x=2; public void incr(){x++;} public void decr(){x--;} public void print(){ Console.WriteLine("Value={0}",x); }

62 Nov 2005 SDP-MSc Slide 62 : public void step2() { Operation o = new Operation(incr); o(); o();} public void stepandprint(){ Operation o = new Operation(incr); o += new Operation(print); o(); }

63 Nov 2005 SDP-MSc Slide 63 public class Test99{ public static void Main(string[] args){ Test t=new Test(); t.print(); t.step2(); t.stepandprint(); Console.Read(); }}

64 Nov 2005 SDP-MSc Slide 64

65 Nov 2005 SDP-MSc Slide 65 Higher Order Functions Using Delegates

66 Nov 2005 SDP-MSc Slide 66 Higher Order Functions A Function which takes another function as parameter Function can also be returned as a result I.e Functions treated as Objects increment :: Int -> Int increment n = (n+1)

67 Nov 2005 SDP-MSc Slide 67 Higher Order Functions increment :: Int -> Int increment n = (n+1) map1 :: (a -> b) -> [a] -> [b] map1 f [] = [] map1 f (x:xs) = f x : map1 f xs > map1 increment [1,2,3,4] [2,3,4,5]

68 Nov 2005 SDP-MSc Slide 68 Higher Order Functions in C# using delegates using System; using System.Collections; public delegate int OneArgFunction(int x); public class TestHOF1{ public static int apply(int x){ return x+1;} : increment :: Int -> Int increment n = (n+1)

69 Nov 2005 SDP-MSc Slide 69 : public static void map(OneArgFunction f, int[] a) {for (int i=0;i<a.Length;i++){ a[i]=f(a[i]);} } public static void Main(string[] args){ int[] arr={3,4,5,6,7}; map(new OneArgFunction(apply),arr); for (int i=0; i<5;i++){ Console.WriteLine("["+arr[i]+"]");} Console.Read(); }}

70 Nov 2005 SDP-MSc Slide 70

71 Nov 2005 SDP-MSc Slide 71 Write a function which : - takes a function & list of Ints as paramemets - applies function to first & last element - return result as sum of these two wlaues >sum_fl increment [3,4,5,6] 11 i.e 4 + 7 sum_fl :: (Int -> Int) -> [Int] -> Int sum_fl f (x:xs) = f x + f (last xs) Now the Java Version -->

72 Nov 2005 SDP-MSc Slide 72 public delegate int Operation(int x); public class TestHOF1{ public static int apply(int x){ return x+1;}

73 Nov 2005 SDP-MSc Slide 73 : public static int sum_fl(Operation f, int[] a) { return f(a[0])+ f(a[a.Length-1]); } public static void Main(string[] args){ int[] arr={3,4,5,6,7}; Operation o=new Operation(apply); int res=sum_fl(o,arr); Console.WriteLine("Sum of 1st & Last= {0}",res); Console.Read(); }}

74 Nov 2005 SDP-MSc Slide 74

75 Nov 2005 SDP-MSc Slide 75 Another Example Add.op(2,3) -> 5 apply_op (Add.op, [3,4,5,6,7]) -> 25

76 Nov 2005 SDP-MSc Slide 76 using System; using System.Collections; public delegate int Operation(int x, int y); public class TestHOF1{ public static int op(int x, int y){ return x+y;} :

77 Nov 2005 SDP-MSc Slide 77 : public static int apply_op(Operation f, int[] a) {int res=0; for (int i=0; i<a.Length;i++) {res = f(res,a[i]);} return res; } public static void Main(string[] args){ int[] arr={3,4,5,6,7}; Operation o=new Operation(op); int res=apply_op(o, arr); Console.WriteLine("Sum of elements= "+res); Console.Read(); }}

78 Nov 2005 SDP-MSc Slide 78

79 Nov 2005 SDP-MSc Slide 79 Exercise 1 Large implemements Validate – delegate type testval 8 returns false testval 11 returns true - values >= 10 test_list testval [2, 12, 8, 17, 9] returns false test_list testval [12, 13, 18, 17,19] returns true

80 Nov 2005 SDP-MSc Slide 80 Exercise 2 Bigger implements Validate– delegate type compare 8,9 returns false compare 9,8 returns true compare 9,9 returns false test_list compare [12, 8, 17, 9] 9 returns false test_list compare [12, 8, 17, 9] 7 returns true

81 Nov 2005 SDP-MSc Slide 81 Filter Example Small 8 returns true Small 11 returns false myfilter small, [2, 12, 8, 17, 9], 0 returns [2, 8, 9]

82 Nov 2005 SDP-MSc Slide 82 using System; using System.Collections; public delegate bool Validate(int n); public class TestHOF1{ public static bool testval(int n){ if (n<10) return true; else return false; }

83 Nov 2005 SDP-MSc Slide 83 public static void myFilter(Validate f, ArrayList v, int index) { if (v.Count==0) return; if (index==v.Count) return; else {int el=(int)v[index]; if (f(el)==false) { v.RemoveAt(index); myFilter(f,v,index);} else myFilter(f,v,index+1);} } :

84 Nov 2005 SDP-MSc Slide 84 public static void Main(string[] args){ ArrayList a=new ArrayList(); a.Add(2); a.Add(19); a.Add(9); a.Add(14); a.Add(9); a.Add(8); Validate v=new Validate(testval); myFilter(v,a,0); for (int i=0; i<a.Count;i++){ int val=(int)a[i]; Console.WriteLine("["+val+"]");} Console.Read(); }}

85 Nov 2005 SDP-MSc Slide 85

86 Nov 2005 SDP-MSc Slide 86 Another Filter Example greater 8 9 returns false greater 9 8 returns true greater 9 9 returns false myfilter greater, [2, 12, 4, 3, 9], 3, 0 returns [12, 4, 9]

87 Nov 2005 SDP-MSc Slide 87 public delegate bool Condition(int x, int y); public class TestHOF1{ public static bool test(int x,int y){ if (x>y) return true; else return false; }

88 Nov 2005 SDP-MSc Slide 88 public static void myFilter(Condition f,ArrayList v, int val,int index) { if (v.Count==0) return; if (index==v.Count) return; else { int el=(int)v[index]; if (f(el,val)==false) { v.RemoveAt(index); myFilter(f,v,val,index);} else myFilter(f,v,val,index+1); }

89 Nov 2005 SDP-MSc Slide 89 public static void Main(string[] args){ ArrayList a=new ArrayList(); a.Add(7); a.Add(19); a.Add(9); a.Add(6); a.Add(14); a.Add(24); Condition c=new Condition(test); myFilter(c,a,8,0); for (int i=0; i<a.Count;i++){ int val=(int)a[i]; Console.WriteLine("["+val+"]");} Console.Read(); }}

90 Nov 2005 SDP-MSc Slide 90

91 Nov 2005 SDP-MSc Slide 91 Modify previous Filter Example in 2 ways equal 8 9 returns false equal 9 9 returns true filter_Out equal, [3, 12, 4, 3, 9], 3, 0 returns [12, 4, 9] Exercise 3


Download ppt "Nov 2005 SDP-MSc Slide 1 Section 10 Functional Programming in C#"

Similar presentations


Ads by Google