{# —— Umami 统计(Cloud 版)—— #}

5.2.11

 

题目

Use fix and the encoding of lists from Exercise 5.2.8 to write a function that sums lists of Church numerals.

解答

第一次写出了这个答案:

s=λf. λt. test (isnil t) c0 (plus (head t) (f (tail t)))sum=fix s

然而,由于

tru=λt. λf. t

这里不存在常见编程语言的短路特性,由于求值策略是 call-by-value,必须先计算 f 才能应用,也就是最内层 t=nil 时会对 (plus (head t) (f (tail t))) 求值,产生错误。

因此,使用 η - 展开,改为:

s=λf. λt. test (isnil t) (λx. c0) (λx. (plus (head t) (f (tail t)))) c0sum=fix s

这样,所有分支都不会提前求值,直到被选择并应用于 c0