【发布时间】:2014-08-24 06:26:17
【问题描述】:
在课堂上,我们使用以下球拍结构为组合语言 (lanG) 编写了一个解释器。
(struct const (n))
(struct bool (b))
(struct join (e1 e2))
(struct if-then-else (b e1 e2))
(struct negate (e))
(struct add (e1 e2))
(struct multiply (e1 e2))
(struct head (e)) ;returns the head of the list
(struct tail (e)) ;returns the tail of the list
(struct biggerThan (e1 e2))
这种语言的宏被定义为球拍函数。一个简单的例子是:
(define (threeTimes x)
(add x (add x x)))
使用它看起来像:
(lanG (threeTimes (const 3)))
这会产生一个答案:
(const 9)
现在我的问题。考试中有一个任务,我们必须编写一个宏 sumAtEvenAndOdd,它将对语言常量列表求和,
使用连接结构并返回由偶数位置的元素总和和元素总和组成的一对值
在奇数位置。
这样的列表的一个例子是:
(join (const 3) (join (const 2) (const 5))) ;lanG list with no null at the end
它的结果是:
(join (const 2) (const 8))
我尝试通过将列表转换为球拍列表、使用元素压缩位置、过滤列表中的奇数或偶数元素来解决此问题, 并使用这些列表的总和生成对。这行得通,但我过于复杂了。教授说解法大概有5行。
提前感谢您的帮助。
【问题讨论】:
-
是的,它是一个过程/解释器,它解析用上述结构编写的程序。对不起,但我宁愿不发布源代码,这样我就不会惹上麻烦。我感兴趣的主要是,我将如何遍历这样的列表。通常一个列表会以 null 或其他东西结尾,这样人们就会知道何时停止对其进行递归。