Chapter 15 Functional Programming Languages (Scheme Examples) Dr. Muhammad Shafique

advertisement
Chapter 15
Functional Programming Languages
(Scheme Examples)
Dr. Muhammad Shafique
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
1
Introduction to Functional
Programming using Scheme
(http://htdp.org)
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
2
Getting the Software – Installation and Related Issues
• Download the programming environment from http://drscheme.org
• Dr Scheme supports several variants of the Scheme programming
language.
• To begin with (derived from http:// htdp.org), we use “Beginning
Student Scheme”).
• You can select the language by:
• Language  Choose Language  Beginning Student
Scheme.
• Click “Run” or “Execute” for your changes to take
effect.
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
3
Dr. Scheme
• The programming environment
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
4
Part 2
Scheme Examples
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
5
Example 1
• Develop a Scheme function to compute the factorial of a
given number
(define (factorial n)
(if
(< n 1)
1
(* n (factorial (- n 1)))
)
)
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
6
Example 1
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
7
Example 2
• Write a scheme function that computes the sum of all
elements of a given list.
(define evens ‘(0 2 4 6 8))
(define (sum alist)
(if
(null? alist) 0
(+ (car alist) (sum (cdr alist)))
)
)
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
8
Example 2
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
9
Example 3
• Write a scheme function to find the length (number of
elements) of a given list.
(define (length alist)
(if
(null? alist) 0
(+ 1 (length (cdr alist)))
)
)
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
10
Example 3
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
11
Example 4
• Develop a Scheme function that takes two arguments: a
function and a list. The function produces a new list which is
the result of applying the given argument function on the
elements of the given list.
(define (mapcar fun alist)
(if
(null? Alist) ‘()
(cons (fun (car alist) (mapcar fun (cdr alist)))
)
)
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
12
Example 5
• Using the function defined in example 4 write a Scheme
program to compute the square of each element of a given list
(define evens ‘(0 2 4 6 8))
(define (square x (* x x))
(define (mapcar fun alist)
(if
(null? Alist) ‘()
(cons (fun (car alist)) (mapcar fun (cdr alist)))
)
)
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
13
Example 5
ics 313 - 01 (061)
Chapter 15 Functional Programming
Languages
14
Download