Our function sum produces the same result as the built-in function ???+??™ when presented with two arguments, but
sum will not accept an arbitrary number of input parameters:
> (sum 4 3)
7
> (+ 4 3)
7
> (sum 4 3 2)
[Repl(25)] Error: incorrect number of arguments to
#
.
Type (debug) to enter the debugger.
Looping in a functional language is accomplished by recursion, that is, by having the function call itself
repetitively. Indeed, one of the reasons to study functional programming is to become comfortable using recursion.
Even programmers using the popular imperative programming languages can take advantage of recursion,
which can make some programming tasks more compact, self-documenting, and reliable.
For instance, suppose we need a function to compute the factorial of an integer. One way to write such code
in C or Java is this:
int factorial( int n ){
int fact = 1;
while( n > 1 ) {
fact = fact * n;
n--;
}
return fact;
}
This version of the factorial function starts with the number passed in, and then iteratively multiplies that
number by each smaller number until the function works its way down to 1.
A different way to write this function in C or Java, using recursion, is this way:
int factorial( int n ){
if( n <= 1 ) return 1;
return( n * factorial( n-1 ));
}
If the number passed in is greater than 1, the recursive function simply multiplies the number passed in by
the factorial of that number minus 1.
Pages:
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164