灯下 登录
计算机科学 / SICP / 4.4.3 Is Logic Programming Mathematical Logic?

Exercise 4.66 · 习题

Exercise 4.66: Ben has been generalizing the
query system to provide statistics about the company. For example, to find the
total salaries of all the computer programmers one will be able to say

(sum ?amount
(and (job ?x (computer programmer))
(salary ?x ?amount)))

In general, Ben’s new system allows expressions of the form

(accumulation-function ⟨variable⟩
⟨query pattern⟩)

where accumulation-function can be things like sum,
average, or maximum. Ben reasons that it should be a cinch to
implement this. He will simply feed the query pattern to qeval. This
will produce a stream of frames. He will then pass this stream through a
mapping function that extracts the value of the designated variable from each
frame in the stream and feed the resulting stream of values to the accumulation
function. Just as Ben completes the implementation and is about to try it out,
Cy walks by, still puzzling over the wheel query result in
Exercise 4.65. When Cy shows Ben the system’s response, Ben groans,
“Oh, no, my simple accumulation scheme won’t work!”

What has Ben just realized? Outline a method he can use to salvage the

situation.

练习 4.66:Ben 一直在扩展查询系统,以提供公司统计信息。例如,为了求出所有计算机程序员的薪资总和,将可以使用:

(sum ?amount
(and (job ?x (computer programmer))
(salary ?x ?amount)))

一般而言,Ben 的新系统允许以下形式的表达式:

(accumulation-function ⟨variable⟩
⟨query pattern⟩)

其中 accumulation-function 可以是 sum、average 或 maximum 等。Ben 认为实现起来应该轻而易举:只需将查询模式交给 qeval,由此产生一个框架流;然后通过一个映射过程从流中每个框架提取指定变量的值,再将所得值的流传递给累积函数即可。Ben 刚完成实现、正准备试用时,Cy 走了过来,还在为练习 4.65 中 wheel 查询的结果百思不得其解。当 Cy 把系统的响应展示给 Ben 看时,Ben 叹道:"糟了,我这个简单的累积方案行不通!"

Ben 意识到了什么?请概述一种他可以用来挽救局面的方法。

Racket #lang sicp
(sum ?amount
 (and (job ?x (computer programmer))
 (salary ?x ?amount)))
Racket #lang sicp
(accumulation-function ⟨variable⟩
 ⟨query pattern⟩)