Sept 2004 SDP-MSc Slide 1 Section 6 Introduction to Functional Programming.

Slides:



Advertisements
Similar presentations
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
Advertisements

0 PROGRAMMING IN HASKELL Chapter 1 - Introduction.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 2 - First Steps.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Introduction to Functional Programming Notes for CSCE 190 Based on Sebesta,
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
Comp. Eng. SW Lab II: FP with Scheme 1 Computer Eng. Software Lab II , Semester 2, Who I am: Andrew Davison CoE, WiG Lab Office.
0 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Functional Programming in Haskell Motivation through Concrete Examples Adapted from Lectures by Simon Thompson.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Definitions. name :: Type answer :: Int name = expression answer = Definitions associate a name with a value of a certain type is of type greater.
0 PROGRAMMING IN HASKELL Chapter 5 – Introduction, The Hugs System, Types and Classes.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
Nov 2005 SDP-MSc Slide 1 Section 10 Functional Programming in C#
0 PROGRAMMING IN HASKELL Some first steps Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
TIVDM2Functional Programming Language Concepts 1 Concepts from Functional Programming Languages Peter Gorm Larsen.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee.
0 INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Haskell Basics CSCE 314 Spring CSCE 314 – Programming Studio Using GHC and GHCi Log in to unix.cse.tamu.edu (or some other server) From a shell.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Guards1. 2 Let’s test this function. Main> maxi Here is a trace of the function: n m maxi 3 2 Guards or conditions are used to express various cases.
0 PROGRAMMING IN HASKELL Chapter 2 - First Steps.
Haskell Introduction CSCE 314 Spring CSCE 314 – Programming Studio Historical Background 1930s: Alonzo Church develops the lambda calculus, a simple.
Computer Eng. Software Lab II , Semester 2, Who I am: Andrew Davison CoE, WiG Lab Office Functional Programming.
Erik Meijer FP101x - Functional Programming Programming in Haskell - Introduction.
C H A P T E R E I G H T Functional Programming Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
1 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Functional Programming
Lecture 14: Advanced Topic: Functional Programming
CS314 – Section 5 Recitation 9
Functional Programming
Conditional Expressions
What is a Functional Language?
Midterm recap Total was 80 points Distribution range
Programming Languages
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Haskell.
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Programming Languages
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
Introduction to Functional Programming in Racket
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
Functional Programming and Haskell
Functional Programming Lecture 2 - Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Functional Programming and Haskell
Presentation transcript:

Sept 2004 SDP-MSc Slide 1 Section 6 Introduction to Functional Programming

Sept 2004 SDP-MSc Slide 2 Section 6 - References About Haskell Why Functional Programming Matters

Sept 2004 SDP-MSc Slide 3 What is a Functional Language? Functional programming is style of programming in which the primary method of computation is the application of functions to arguments; A functional language is one that supports and encourages the functional style. Opinions differ, and it is difficult to give a precise definition, but generally speaking:

Sept 2004 SDP-MSc Slide 4 Historical Background 1920s s: Alonzo Church and Haskell Curry develop the lambda calculus, a simple but powerful mathematical theory of functions. 4

Sept 2004 SDP-MSc Slide 5 Historical Background 1960s: John McCarthy develops Lisp, the first functional language. Some influences from the lambda calculus, but still retained variable assignments. 5

Sept 2004 SDP-MSc Slide 6 Historical Background 1978: John Backus publishes award winning article on FP, a functional language that emphasizes higher-order functions and calculating with programs. 6

Sept 2004 SDP-MSc Slide 7 Historical Background 1999: The definition of Haskell 98 published, providing a long-awaited stable version of the language. 7

Sept 2004 SDP-MSc Slide 8 Principles- Functional Programs 8 No Side effects No variable assignment A Function has no effect other than calculating its value

Sept 2004 SDP-MSc Slide 9 Key Features- Functional Programs 9 Higher Order Functions Lazy Evaluation Currying Lambda Expressions List Processing

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

Sept 2004 SDP-MSc Slide 11 Functional Programs 11 using System; class Fun1 { public static int sum(int a, int b){ return a+b;} public static void Main(string[] args) { int x=Convert.ToInt32(args[0]); int y=Convert.ToInt32(args[1]); Console.WriteLine("Sum of values:{0}", sum(x,y)); }

Sept 2004 SDP-MSc Slide 12

Sept 2004 SDP-MSc Slide 13 - No side effects 13 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); }

Sept 2004 SDP-MSc Slide 14 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 Next: A counter example Functional Programming -

Sept 2004 SDP-MSc Slide 15 class Fun3 {public static int a,b; // global variables public static int sum(){ return a+b;} public static void Main(string[] args) { a=Convert.ToInt32(args[0]); b=Convert.ToInt32(args[1]); Console.WriteLine("Sum of values:{0}", sum()); a=9; b=8; Console.WriteLine("Sum of values:{0}", sum()); }

Sept 2004 SDP-MSc Slide 16 Sample call produces different results

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

Sept 2004 SDP-MSc Slide 18 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)); }

Sept 2004 SDP-MSc Slide 19

Sept 2004 SDP-MSc Slide 20 Recursion Most Functional Programming Languages use recursion - avoids variable assignment - facilitates Lazy Evaluation

Sept 2004 SDP-MSc Slide 21 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)); }

Sept 2004 SDP-MSc Slide 22 class SumRange { public static int sumr(int s, int e){ int res=0; for(int i=s;i<=e;i++) res=res+i; //assignment return res;} public static void Main(string[] args) { int x=Convert.ToInt32(args[0]); int y=Convert.ToInt32(args[1]); Console.WriteLine("SumRange= "+ sumr(x,y)); }

Sept 2004 SDP-MSc Slide 23 Next: Recursive Version

Sept 2004 SDP-MSc Slide 24 class SumRange { public static int sumr(int s, int e){ if (s==e) return s; else return s+ sumr(s+1,e);} public static void Main(string[] args) { int x=Convert.ToInt32(args[0]); int y=Convert.ToInt32(args[1]); Console.WriteLine("SumRange= {0}", sumr(x,y)); }

Sept 2004 SDP-MSc Slide 25 class Arr1 { public static int add(int[] a, int first){ if (a.Length==0)return 0; if (first==a.Length-1) return a[first]; else return a[first] + add(a,first+1); } public static void Main() { int[] v={3,4,5,6,5}; Console.WriteLine("Sum=: {0}", add(v,0)); } Add elements in array

Sept 2004 SDP-MSc Slide 26 class Arr2 { public static int count_target(int[] a,int first,int target){ if (a.Length==0)return 0; if (first>a.Length-1) return 0; else if (a[first]==target) return 1 + count_target(a,first+1,target); else return 0 + count_target(a,first+1,target); } : Count occurrences of target in array

Sept 2004 SDP-MSc Slide 27 public static void Main(string[] args) { int[] v={3,4,5,6,5}; int t=Convert.ToInt32(args[0]); Console.WriteLine("No of occurences: {0}", count_target(v,0,t)); }}

Sept 2004 SDP-MSc Slide 28 Q1 Write a C# application which contains a recursive function static bool search_target(int[] a,int first,int target){ which return ‘true’ if ‘target’ is an element of array ‘a’ otherwise returns ‘false’ e.g. search_target([2,3,4], 0, 3) returns true Exercises:

Sept 2004 SDP-MSc Slide 29 Q2 Write a C# application which contains a recursive function static bool gr_than_tar(int[] a,int first,int target){ which return ‘true’ if all elements of array ‘a’ are > target otherwise returns ‘false’ e.g. gr_than_tar([2,3,4], 0, 1) returns true gr_than_tar([2,3,4], 0, 2) returns false Exercises:

Sept 2004 SDP-MSc Slide 30 Q3 Write a C# application which contains a recursive function static int largest(int[] a, int first){ which return the maximum element in the Array e.g. largest([2,3,4,1], 0) returns 4

Sept 2004 SDP-MSc Slide 31 Functional Programming Two other key features - List Processing - Polymorphic Types

Sept 2004 SDP-MSc Slide 32 int Add(object) - adds to end bool Contains(object) int indexOf(object) insert( int index, object value ); ========================================= public virtual object this[ int index ] {get; set;} // accessor e.g object el=alist[2]; // gets 3 rd element alist[1]=“abc”; ========================================== ArrayList - Collection Class

Sept 2004 SDP-MSc Slide 33 public virtual int Count {get;} // number of elements int size= alist.Count =========================================== void RemoveAt(int) - remove el at given index setElementAt(Object, int) Sort() public virtual int Capacity {get; set;} // sets,gets max size // 16 by default Alternative: ArrayList text = new ArrayList(newCapactity)

Sept 2004 SDP-MSc Slide 34 using System; using System.Collections; class Vec1 { public static void Main() { ArrayList a=new ArrayList(); a.Add("a"); a.Add("b"); a.Add("c"); for(int i=0; i<a.Count;i++) Console.WriteLine(" {0}“, a[i]); }

Sept 2004 SDP-MSc Slide 35 class Vec2 { public static void Main() { ArrayList a=new ArrayList(); a.Add(1); a.Add(2); a.Add(3); for(int i=0; i<a.Count;i++) Console.WriteLine(" {0}", a[i]); }

Sept 2004 SDP-MSc Slide 36 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));} }

Sept 2004 SDP-MSc Slide 37 Next Fuctional Version

Sept 2004 SDP-MSc Slide 38 class Vec4 { public static int total(ArrayList vec, int first) { if (vec.Count == 0) return 0; if (first == vec.Count - 1) return (int)vec[first]; else return (int)vec[first] + total(vec, first + 1); }

Sept 2004 SDP-MSc Slide 39 : public static void Main(string[] args) { ArrayList v = new ArrayList(); v.Add(Convert.ToInt32(args[0])); v.Add(Convert.ToInt32(args[1])); v.Add(Convert.ToInt32(args[2])); Console.WriteLine("Sum of Elements: {0}",total(v,0)); Console.Read(); }

Sept 2004 SDP-MSc Slide 40 Now to search vector [3,4,5] for a value

Sept 2004 SDP-MSc Slide 41 class Vec5 { public static bool our_search(ArrayList vec,int first,int target) { if (vec.Count == 0) return false; if (first > vec.Count - 1) return false; else if ((int)vec[first]== target) return true; else return our_search(vec, first + 1,target); }

Sept 2004 SDP-MSc Slide 42 public static void Main(string[] args) { ArrayList v = new ArrayList(); v.Add(3); v.Add(4); v.Add(5); int t = Convert.ToInt32(args[0]); Console.WriteLine("Element found: {0}", our_search(v, 0, t)); Console.Read(); }

Sept 2004 SDP-MSc Slide 43 Counting Els in [3,4,5,2]

Sept 2004 SDP-MSc Slide 44 class Vec6 { public static int our_count(ArrayList vec, int first, int target) { if (vec.Count == 0) return 0; if (first > vec.Count - 1) return 0; else if ((int)vec[first]== target) return 1+our_count(vec,first+1,target); else return 0+our_count(vec,first+1,target); }

Sept 2004 SDP-MSc Slide 45 : public static void Main(string[] args) { ArrayList v = new ArrayList(); v.Add(3); v.Add(4); v.Add(5); v.Add(3); int t = Convert.ToInt32(args[0]); Console.WriteLine("No of Element found: {0}", our_count(v, 0, t)); Console.Read(); }

Sept 2004 SDP-MSc Slide 46 Q3 Write a java application which contains a recursive function static boolean gr_than_tar(Vector v,int first,int target){ which return ‘true’ if all elements of array ‘a’ are > target otherwise returns ‘false’ e.g. gr_than_tar([2,3,4], 0, 1) returns true gr_than_tar([2,3,4], 0, 2) returns false Exercises:

Sept 2004 SDP-MSc Slide 47 Q4 Write a java application which contains a recursive function static int largest(int[] a, int first){ which return the maximum element in the Array e.g. largest([2,3,4,1], 0) returns 4

Sept 2004 SDP-MSc Slide 48 Q5. Rewrite Q4 but this time using a Vector Write a java application which contains a recursive function static int largest(Vector v,int first){ which return the maximum element in the Vector e.g. largest([2,3,4,1], 0) returns 4

Sept 2004 SDP-MSc Slide 49 Functional Programming -other key features Higher Order Functions Lazy Evaluation Currying Lambda expressions (Nameless functions) Need a pure Functional Language to implement these fully we will briefly look at Haskell

Sept 2004 SDP-MSc Slide 50 What is Hugs? Hugs is an interactive Haskell system, and is the most widely used implementation of Haskell; Hugs is available on the web from: Download has type ‘.msi’ may have to download a mircosoft application to unzip this also

Sept 2004 SDP-MSc Slide 51 From File Manager Change to folder c:/Program Files/Hugs98/lib double click on “Prelude.hs Starting Hugs

Sept 2004 SDP-MSc Slide 52 Starting Hugs % hugs __ __ __ __ ____ ___ _________________________________________ || || || || || || ||__ Hugs 98: Based on the Haskell 98 standard ||___|| ||__|| ||__|| __|| Copyright (c) ||---|| ___|| World Wide Web: || || Report bugs to: || || Version: February 2000 _________________________________________ Haskell 98 mode: Restart with command line option -98 to enable extensions Reading file "/usr/local/share/hugs/lib/Prelude.hs": Hugs session for: /usr/local/share/hugs/lib/Prelude.hs Type :? for help Prelude>

Sept 2004 SDP-MSc Slide 53 The Hugs > prompt means that the Hugs system is ready to evaluate an expression. For example: > 5+2*3 11 > (5+2)*3 21 > sqrt (3^2 + 4^2) 5.0

Sept 2004 SDP-MSc Slide 54 The Standard Prelude The library file Prelude.hs provides a large number of standard functions. In addition to the familiar numeric functions such as + and *, the library also provides many useful functions on lists. Calculating the length of a list: > length [1,2,3,4] 4

Sept 2004 SDP-MSc Slide 55 > reverse [1,2,3,4] [4,3,2,1] > [1,2,3] ++ [4,5,6] [1,2,3,4,5,6] > head [1,2,3,4] 1 > tail [1,2,3,4] [2,3,4] > last [1,2,3,4] 4

Sept 2004 SDP-MSc Slide 56 double x = x + x quadruple x = double (double x) When developing a Haskell script, it is useful to keep two windows open, one running an editor for the script, and the other running Hugs. Start an editor, type in the following two function definitions, and save the script as test.hs Save in: c:/Program Files/Hugs98/lib From Hugs prompt type > :load “test.hs”

Sept 2004 SDP-MSc Slide 57 > quadruple > double 2 4 Now both Prelude.hs and test.hs are loaded, and functions from both scripts can be used: increment :: Int -> Int increment n = (n+1)

Sept 2004 SDP-MSc Slide 58 larger :: Int -> Int -> Int larger a b = if a > b then a else b Larger

Sept 2004 SDP-MSc Slide 59 > :r If we modify file “test.hs” must reload

Sept 2004 SDP-MSc Slide 60 factorial :: Int -> Int factorial n = if n==0 then 1 else n * factorial (n - 1)

Sept 2004 SDP-MSc Slide 61 search :: Int -> [Int] -> Bool search t [] = False search t (x:xs) = if x == t then True else search t xs > search 5 [3,4,5,6] True > search 8 [3,4,5,6] False

Sept 2004 SDP-MSc Slide 62 count_els :: [Int] -> Int count_els [] = 0 count_els (x:xs) = 1 + count_els xs > count_els [3,4,5,6] 4

Sept 2004 SDP-MSc Slide 63 > count_occur 4 [3,4,5,6,4] 2 count_occur :: Int -> [Int] -> Int count_occur t [] = 0 count_occur t (x:xs) = if x==t then 1 + count_occur t xs else 0 + count_occur t xs

Sept 2004 SDP-MSc Slide 64 add_els :: [Int] -> Int add_els [] = 0 add_els (x:xs) = x + add_els xs > add_els [3,4,5,6] 18

Sept 2004 SDP-MSc Slide 65 mylast :: [Int] -> Int mylast (x:xs) = if xs ==[] then x else mylast xs add_fl :: [Int] -> Int add_fl [] = 0 add_fl (x:xs) = x + mylast xs > add_fl[3,4,5,6] 9

Sept 2004 SDP-MSc Slide 66 Q1a. Define function ‘decrement n’ decrement 10 9 Q1b smaller Q1c equal 8 6 equal True Q1d length [2,3,4,4] 4 Q1e product [ 2, 3,4 ] 24 i.e. 2 * 3 * 4 Huskell

Sept 2004 SDP-MSc Slide 67 Q2. Compete the following function count_small :: [Int]->Int count_small [4, 5, 16, 2, 6, 22] return 4 count_small [ ] returns 0 Returns the number of items in the list less than 10

Sept 2004 SDP-MSc Slide 68 Q3. Compete the following function max :: [Int]->Int max [4,5,6,2,6,1] returns 6 max [ ] returns 0

Sept 2004 SDP-MSc Slide 69 Q4. Compete the following function gr_than_tar :: [Int]->Int-> Bool gr_than_tar [4,5,6,2,6] 1 returns True gr_than_tar [4,5,6,2,6] 2 returns False i.e Are all els in Array greater than target Huskell Q2

Sept 2004 SDP-MSc Slide 70 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)

Sept 2004 SDP-MSc Slide 71 The Map Function The higher-order library function called map applies a function to every element of a list. map :: (a  b)  [a]  [b] For example: > map increment [1,2,3,4] [2,3,4,5]

Sept 2004 SDP-MSc Slide 72 The map function can be defined as 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]

Sept 2004 SDP-MSc Slide 73 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 sum_fl :: (Int -> Int) -> [Int] -> Int sum_fl f (x:xs) = f x + f (last xs)

Sept 2004 SDP-MSc Slide 74 small :: Int -> Bool small n = if n<10 then True else False myfilter :: (a -> Bool) -> [a] -> [a] myfilter p [] = [] myfilter p (x:xs) = if p x == True then x : myfilter p xs else myfilter p xs

Sept 2004 SDP-MSc Slide 75 Q5. Define a function ‘greater’ greater :: Int -> Int ->Bool greater 2 3 False greater 3 2 True

Sept 2004 SDP-MSc Slide 76 Q6. Now define a function myfilter2 :: (Int -> Int -> Bool) -> [Int] -> Int -> [Int] myfilter greater [3,4,5,6,2,7] 3 [4,5,6,7] I.e returns all values in List greater than 3

Sept 2004 SDP-MSc Slide 77 Q7. Define a function ‘large’ Outline a Haskell function ‘large ’ which takes an integer as parameter and returns True if the value is greater than 9 Examples: large 16 returns True large 4 returns False

Sept 2004 SDP-MSc Slide 78 Q8. This question concerns Higher Order Functions in Haskell. Outline a Haskell function ‘count_qualify’ which takes 2 parameters -a function (like large ) which takes an integer and returns a Boolean -a list of integers Our new higher function will apply the supplied function to each element of the list in turn. The overall function will count and return the number of elements in the list satisfying the inner function Examples: count_qualify large [15, 6, 17, 5, 18] returns 3 count_qualify large [5, 6, 17, 5, 8] returns 1

Sept 2004 SDP-MSc Slide 79 Useful Hugs Commands CommandMeaning :l nameload script name :rreload current script :e nameedit script name :eedit current script :t exprshow type of expr :?show all commands :qquit