計算機科学のブログ

Building Abstractions with Functions - The Elements of Programming - Conditional Expressions and Predicates - applicative-order evaluatrion, normal-order-evaluation

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.1(The Elements of Programming)、1.1.6(Conditional Expressions and Predicates)、Exercise 1.5の解答を求めてみる。

applicative-order evaluation

  1. test(0, p())
  2. test(0, p())

normal-order evaluation

  1. test(0, p())
  2. 0 === 0 ? 0 : p()
  3. true ? 0 : p()
  4. 0

applicative-orderなJavaScriptとnormal-orderなHaskellで実際に確認してみる。

コード

function p() {
    return p();
}
function test(x, y) {
    return x === 0 ? 0 : y;
}

console.log(test(0, p()));

コード

p :: t
p = p

test :: (Eq a, Num a, Num p1) => a -> p2 -> p1
test x y =
    if x == 0
    then 0
    else p

main :: IO ()
main = do
    print $ test 0 p

入出力結果(Terminal, Zsh)

% node answer1.5.js  
/Users/…/answer1.5.js:2
    return p();
    ^

RangeError: Maximum call stack size exceeded
    at p (/Users/…/answer1.5.js:2:5)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
    at p (/Users/…/answer1.5.js:2:12)
% runghc answer1.5.hs
0
%