東京大学 情報理工学系研究科 コンピュータ科学専攻 2023年8月実施 専門科目 問題4
Author
Description
Let us consider the following function
int f(int x)
{
if (x <= 0) return x + 1;
else return f(f(x - 2));
}
For example,
Answer the following questions:
(1) Give the number of calls of the function
(2) Show that the return value of
(3) Let
(4) Let
(5) Give an example of a program that does not terminate with the call-by-value strategy but terminates with the call-by-name strategy.
让我们考虑以下在类似 C 的编程语言中描述的函数
int f(int x)
{
if (x <= 0) return x + 1;
else return f(f(x - 2));
}
例如,
回答以下问题:
(1) 计算
(2) 证明对于每一个非负整数
(3) 设
(4) 设
(5) 给出一个程序的例子,该程序在按值调用策略下不终止,但在按名调用策略下终止。
Kai
(1)
First, let's evaluate
To summarize:
calls , directly returns , is equivalent to which involves 3 calls as shown in the question statement.
Thus, the total number of calls during the evaluation of
(2)
Let's prove this statement by induction on
Base Case:
For
So,
Inductive Step:
Assume that
By the inductive hypothesis,
Therefore, by induction,
(3)
To determine the number of calls during
Let
Starting with the base cases:
So for even
Thus,
For odd
So we can express it as:
(4)
When using call-by-name, the function argument is not evaluated at the moment of the function call, but instead, every occurrence of the argument in the function body is replaced by the original expression.
For the function
Each
(5)
Consider the following function:
int first(int x, int y)
{
return x;
}
int inf(int x)
{
return inf(x+1)
}
If we call this with:
first(2, inf(1))
Here, inf(x)
has an infinite depth of recursion. the program will not terminate under call-by-value, because inf(1)
will be evaluated before entering first
. However, under call-by-name, inf(1)
will be skipped, since inf
is actually never used in the function body, leading to termination.
Knowledge
递归函数 编程语言 调用策略 值调用 名调用
难点思路
在解决这道题目时,主要的难点在于理解不同调用策略如何影响递归函数的计算次数和返回值。尤其是对于 call-by-name 策略,理解参数传递的延迟计算(lazy evaluation)如何导致不同的函数行为。
解题技巧和信息
- 对于递归函数,可以利用归纳法证明递归终止条件和返回值的一致性。
- 需要熟悉 call-by-value 和 call-by-name 两种调用策略的差异,尤其是它们如何影响函数调用的次数和执行顺序。
重点词汇
- Call-by-Value: 值调用
- Call-by-Name: 名调用
- Recursion: 递归
- Evaluation Strategy: 计算策略
参考资料
- Programming Languages: Concepts and Constructs (Chapter on Evaluation Strategies)
- Types and Programming Languages, Benjamin C. Pierce (Chapter on Operational Semantics)