Top Banner
Sept 2004 1 Section 6 Introduction to Functional Programming
79

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

Jan 01, 2016

Download

Documents

Evelyn Nelson
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Sept 2004 SDP-MSc Slide 1 Section 6 Introduction to Functional Programming.

Sept 2004 SDP-MSc Slide

1

Section 6

Introduction to Functional Programming

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

Sept 2004 SDP-MSc Slide

2

Section 6 - References

About Haskell

http://www.haskell.org/aboutHaskell.html

Why Functional Programming Matters

http://www.md.chalmers.se/~rjmh/Papers/whyfp.pdf

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

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:

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

Sept 2004 SDP-MSc Slide

4

Historical Background1920s - 1940s:

Alonzo Church and Haskell Curry develop the lambda calculus, a simple but powerful mathematical theory of functions. 4

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

Sept 2004 SDP-MSc Slide

5

Historical Background1960s:

John McCarthy develops Lisp, the first functional language. Some influences from the lambda calculus, but still retained variable assignments.

5

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

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

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

Sept 2004 SDP-MSc Slide

7

Historical Background1999:

The definition of Haskell 98 published, providing a long-awaited stable version of the language.

7

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

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

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

Sept 2004 SDP-MSc Slide

9

Key Features- Functional Programs

9

•Higher Order Functions

•Lazy Evaluation

•Currying

•Lambda Expressions

•List Processing

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

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

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

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));}

}

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

Sept 2004 SDP-MSc Slide

12

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

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);

}

}

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

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 -

Page 15: Sept 2004 SDP-MSc Slide 1 Section 6 Introduction to 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());

}

}

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

Sept 2004 SDP-MSc Slide

16

Sample call produces different results

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

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

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

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));

}

}

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

Sept 2004 SDP-MSc Slide

19

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

Sept 2004 SDP-MSc Slide

20

Recursion

Most Functional Programming Languages use recursion

- avoids variable assignment

- facilitates Lazy Evaluation

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

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)); }

}

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

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)); }

}

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

Sept 2004 SDP-MSc Slide

23

Next: Recursive Version

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

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));

} }

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

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

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

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

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

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)); }}

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

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:

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

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:

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

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

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

Sept 2004 SDP-MSc Slide

31

Functional Programming

Two other key features

- List Processing

- Polymorphic Types

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

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 3rd element alist[1]=“abc”;==========================================

ArrayList - Collection Class

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

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 defaultAlternative:ArrayList text = new ArrayList(newCapactity)

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

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]);

}}

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

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]);

}}

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

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));} }

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

Sept 2004 SDP-MSc Slide

37

Next Fuctional Version

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

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); }

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

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(); }}

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

Sept 2004 SDP-MSc Slide

40

Now to search vector [3,4,5] for a value

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

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); }

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

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(); }}

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

Sept 2004 SDP-MSc Slide

43

Counting Els in [3,4,5,2]

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

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); }

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

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(); }}

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

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:

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

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

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

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

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

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

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

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:

www.haskell.org/hugs

Download has type ‘.msi’ may have to download a mircosoft application to unzip this also

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

Sept 2004 SDP-MSc Slide

51

•From File Manager

•Change to folder

c:/Program Files/Hugs98/lib

•double click on “Prelude.hs

Starting Hugs

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

Sept 2004 SDP-MSc Slide

52

Starting Hugs% hugs

__ __ __ __ ____ ___ _________________________________________|| || || || || || ||__ Hugs 98: Based on the Haskell 98 standard||___|| ||__|| ||__|| __|| Copyright (c) 1994-1999||---|| ___|| World Wide Web: http://haskell.org/hugs|| || Report bugs to: [email protected]|| || 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.hsType :? for help

Prelude>

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

Sept 2004 SDP-MSc Slide

53

The Hugs > prompt means that the Hugs system is ready to evaluate an expression.

For example:> 5+2*311

> (5+2)*321

> sqrt (3^2 + 4^2)5.0

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

Sept 2004 SDP-MSc Slide

54

The Standard PreludeThe 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

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

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

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

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”

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

Sept 2004 SDP-MSc Slide

57

> quadruple 1040

> double 24

Now both Prelude.hs and test.hs are loaded, and functions from both scripts can be used:

increment :: Int -> Intincrement n = (n+1)

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

Sept 2004 SDP-MSc Slide

58

larger :: Int -> Int -> Intlarger a b = if a > b then a else b

Larger

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

Sept 2004 SDP-MSc Slide

59

> :r

If we modify file “test.hs”

must reload

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

Sept 2004 SDP-MSc Slide

60

factorial :: Int -> Intfactorial n = if n==0 then 1 else n * factorial (n - 1)

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

Sept 2004 SDP-MSc Slide

61

search :: Int -> [Int] -> Boolsearch t [] = Falsesearch 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

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

Sept 2004 SDP-MSc Slide

62

count_els :: [Int] -> Intcount_els [] = 0count_els (x:xs) = 1 + count_els xs

> count_els [3,4,5,6]4

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

Sept 2004 SDP-MSc Slide

63

> count_occur 4 [3,4,5,6,4]2

count_occur :: Int -> [Int] -> Intcount_occur t [] = 0count_occur t (x:xs) = if x==t then 1 + count_occur t xs else 0 + count_occur t xs

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

Sept 2004 SDP-MSc Slide

64

add_els :: [Int] -> Intadd_els [] = 0add_els (x:xs) = x + add_els xs

> add_els [3,4,5,6]18

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

Sept 2004 SDP-MSc Slide

65

mylast :: [Int] -> Intmylast (x:xs) = if xs ==[] then x else mylast xs add_fl :: [Int] -> Intadd_fl [] = 0add_fl (x:xs) = x + mylast xs

> add_fl[3,4,5,6]9

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

Sept 2004 SDP-MSc Slide

66

Q1a. Define function ‘decrement n’

decrement 10 9

Q1b smaller 8 6 6

Q1c equal 8 6 equal 8 8 6 True

Q1d length [2,3,4,4] 4

Q1e product [ 2, 3,4 ] 24i.e. 2 * 3 * 4

Huskell

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

Sept 2004 SDP-MSc Slide

67

Q2. Compete the following function count_small :: [Int]->Int

count_small [4, 5, 16, 2, 6, 22] return 4count_small [ ] returns 0

Returns the number of items in the list less than 10

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

Sept 2004 SDP-MSc Slide

68

Q3. Compete the following function max :: [Int]->Int

max [4,5,6,2,6,1] returns 6max [ ] returns 0

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

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 Truegr_than_tar [4,5,6,2,6] 2 returns False

i.e Are all els in Array greater than target

Huskell Q2

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

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 -> Intincrement n = (n+1)

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

Sept 2004 SDP-MSc Slide

71

The Map FunctionThe 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]

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

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]

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

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 4 + 7

sum_fl :: (Int -> Int) -> [Int] -> Intsum_fl f (x:xs) = f x + f (last xs)

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

Sept 2004 SDP-MSc Slide

74

small :: Int -> Boolsmall 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

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

Sept 2004 SDP-MSc Slide

75

Q5. Define a function ‘greater’

greater :: Int -> Int ->Bool

greater 2 3 False

greater 3 2True

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

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

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

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

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

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

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

Sept 2004 SDP-MSc Slide

79

Useful Hugs CommandsCommand Meaning

:l name load script name:r reload current script:e name edit script name:e edit current script:t expr show type of expr:? show all commands:q quit