計算機科学のブログ

Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Functions as Returned Values - smooth, average

Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 1(Building Abstractions with Functions)、1.3(Formulating Abstractions with Higher-Order Functions)、1.3.4(Functions as Returned Values)、Exercise 1.44の解答を求めてみる。

コード

function compose(f, g) {
    return x => f(g(x));
}
function repeated(f, n) {
    return n === 1 ?
        f :
        compose(f, repeated(f, n - 1));
}
const dx = 0.00001;
function smooth(f) {
    return x => (f(x - dx) + f(x) + f(x + dx)) / 3;
}
function n_fold_smooth(f, n) {
    return repeated(smooth, n)(f);
}
function iter(f) {
    function g(x) {
        if (x < 3) {
            console.log(f(x));
            g(x + 1);
        } else {
            console.log();
        }
    }
    g(-2);
}

function f(x) {
    return Math.random() * 100;
}

iter(f);

iter(n_fold_smooth(f, 1));
iter(n_fold_smooth(f, 2))
iter(n_fold_smooth(f, 3))
iter(n_fold_smooth(f, 4))
iter(n_fold_smooth(f, 10))

入出力結果(Terminal, Zsh)

% node answer1.44.js
41.216797414664505
34.14831294603191
14.71555359953831
64.2893652584638
12.277717810003752

29.91960939354828
39.13084500432249
57.04412362898396
79.44094538286896
59.13927389083599

41.75346791323286
61.24544706805634
47.481155696112275
50.650677155618915
55.500072283414234

43.119388878134316
48.27949256873571
54.73160990476933
47.833702580554494
47.08577729759145

51.69000100619593
49.9072368562316
50.29317383574602
49.08670776499398
45.482380407428764

50.05396369442687
49.86723339735411
50.06570363990634
50.11529541337399
49.96811240725683

%