about summary refs log tree commit diff stats
path: root/qjs/fact.js
blob: c5d718e42b1c2c1053831bc94a8b85561ac3fb86 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import {assert} from "utils.js";


// https://sourceacademy.org/sicpjs/1.2.1#fig-1.6
// recursive 
function factorial_01(n) {
    return n === 1 
           ? 1
           : n * factorial_01(n - 1);
} 
assert(factorial_01(7) === 5040, 'factorial_01 returns an incorrect result.')
console.log(factorial_01(7), 'v01')


// https://sourceacademy.org/sicpjs/1.2.1#fig-1.8 
// iterative
function factorial_02(n) {
    return fact_iter(1, 1, n);
}
function fact_iter(product, counter, max_count) {
    return counter > max_count
           ? product
           : fact_iter(counter * product,
                       counter + 1,
                       max_count);
}
assert(factorial_02(7) === 5040, 'factorial_02 returns an incorrect result.')
console.log(factorial_02(7), 'v02')


// FROM SICP
// In contrasting iteration and recursion, we must be careful not to confuse the 
// notion of a recursive process with the notion of a recursive function. When we 
// describe a function as recursive, we are referring to the syntactic fact that 
// the function declaration refers (either directly or indirectly) to the function 
// itself. But when we describe a process as following a pattern that is, say, 
// linearly recursive, we are speaking about how the process evolves, not about 
// the syntax of how a function is written.