gpt4 book ai didi

方案:不使用 if/cond 解决任务?

转载 作者:行者123 更新时间:2023-12-02 06:57:37 25 4
gpt4 key购买 nike

因此,从理论上讲,我得到了相当简单的任务。

“创建一个过程,将整数作为参数。如果整数为 0,则返回 0。如果整数小于 0,则返回 -1。如果整数大于 0,则返回 1。

使用 if/cond 解决此任务(唯一允许的特殊形式是定义)。”

这是一项非常不切实际的任务,但仍然是我类(class)的要求。几个小时以来,我一直在完成这项任务,所以我希望得到一些意见!

请记住,过程必须返回 -1、0 或 1。#t 或 #f 不够好。

最佳答案

andor 都是if 的特殊版本。例如。

(and a b)           ; is the same as
(if a b #f)

(and a b c ...) ; is the same as
(if a (and b c ...) #f)

(or a b) ; is the same as
(if a
a ; though a is only evaluated once!
b)

(or a b c ...) ; is the same as
(if a
a ; though a is only evaluated once!
(or b c ...))

请注意,对于 3 个或更多元素,结果中包含 andor。您只需应用相同的转换,直到您拥有仅包含 if 的内容。

如果你想要这样的东西:

(if a 'x 'y)

你看到它显然是 (or (and a 'x) 'y) 因为它变成了

(if (if a 'x #f)
(if a 'x #f)
'y)

知道除了 #f 之外的每个值都被认为是真值。在“反向”中执行此操作的基本方法是了解 andor 如何短路,如 if。如果您需要返回一个特殊值而不是您使用的谓词的结果,则:

(and (null? x) 'empty-result)

如果您需要一个假值来继续逻辑,您可以使用

(or (and (null? x) 'empty-result)
(and (pair? x) 'pair-result))

如果您需要一个默认值并且有一个,您只需添加它。

(or (and (null? x) 'empty-result)
(and (pair? x) 'pair-result)
'default-result)

如果您碰巧在外部有,您需要包装一个以获得默认结果:

(or (and ...)
'default-result)

祝你好运!

关于方案:不使用 if/cond 解决任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28234947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com