Prev | Current Page 154 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"


In a functional language, all computation proceeds by means of evaluating functions. Assignment of values to
variables in order to maintain state is not permitted, so we cannot use a variable like ???n??™ to keep track of our progress
in a loop. Looping must be accomplished by recursion. Here is a Scheme function to compute the factorial:
(define factorial
(lambda (n)
(if (<= n 1) 1 (* n (factorial(- n 1)))
)))
Here we also see the conditional execution function if. The if function in Scheme is followed by three
expressions. The first is evaluated for its truth. If the first expression following if is true, the second expression
is evaluated and returned (in this case, if n <= 1, return 1). If the first expression is false, the third expression is
evaluated and returned (in this case, if n > 1, return the product of n and the factorial of n??’1).
We can elaborate on our simple summation function and illustrate some more ideas. Here is a version of
sum that takes a list as an argument. This way, our sum function can compute the sum of any number of
integers:
(define listSum
(lambda (n)
(cond ((null? n) 0)
( (null? (cdr n)) (car n) )
(else (+ (car n) (listSum (cdr n))))
)))
The cond (condition) operator is like multiple if and else-if statements in C or Java.


Pages:
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
gromada CSS Ninja remont warszawa traktorki ogrodowe kolej transsyberyjska