CSC305_FunctionalProgrammingBriefNotes
CSC305_FunctionalProgrammingBriefNotes
FUNCTIONAL PROGRAMMING
Concepts based on Lambda calculus (Mathematical methods)
(define (f1 x y) (+ x y))
(define f2 (lambda (x y)(+ x y)))
(define (f3 x y)(/ (+ x y)(- x y)))
(define f4 (lambda( x y)(/ (+ x y)(- x y))))
Key concepts are (1) expressions, (2) functions, (3) parametric
polymorphism [enables a function to operate on
values of a family of types]→ generic function
Lazy evaluation
int main()
{
int n = 6;
1
define > (define PI 3.142)
> PI
3.142
> (define X 10)
> X
10
> (define Y 'Jamal)
> Y
Jamal
> (define suka '(merah hijau hitam))
> suka
(merah hijau hitam)
> (define suka (quote(merah hijau hitam)))
> suka
(merah hijau hitam)
car and cdr - CAR returns the first element of the list
- CDR returns the remainder elements of the list
2
> (car '(1))
1
> (cdr '(1))
()
>(cdr(cons '(adik abang) '(kakak)))
(kakak)
> (car(cons '(adik abang) '(kakak)))
(adik abang)
3
> (positive? 100)
#t
> (positive? -100)
#f
4
(display "Enter first number : ")
(define x(read))
(display "Enter second number : ")
(define y(read))
(define result(f1 x y))
(display "The summation of ")
(display x)
(display " and ")
(display y)
(display " is ")
(display result)
(define (multiply x y z)(* x y z))
> (f1 7 8)
y greater than x
5
> (define (f2 x) (cond ((= x 1) (+ x 3))
((= x 2) (+ x 2))
(else (+ x 1))))
> (f2 3)
4
6
> (f1 7 3)
wrong option
1 + 2 + 3 + 4 + 5 = 15
Stopper = n=1 return 1
n + f(n-1)
(define (summ x)
(if (= x 1) 1
(+ x (summ (- x 1)))))
7
> (define s (read))
30
> (+ s r)
55
let – to locate value as > (let (( a 100) (b 50)) (+ a b))
local variable 150
8
Exercise 1
Exercise 2
9
Exercise 3
10
Exercise 4
11
Exercise 5
char symbol;
int numl, num2;
cin » symbol » numl » num2;
switch (symbol)
{
case '+': cout « numl + num2;
break;
case '*': cout « numl * num2;
break
case '-': cout « numl - num2;
break
}
Exercise 6
Convert the following recursive function in C into Scheme Language.
int funct1(int n)
{ if (n == 1)
return 1;
else
return (n*n*n + funct1(n-1));
}
12