所以从理论上讲,我的任务相当简单.
"创建一个以整数作为参数的过程.如果整数为0,则返回0.如果整数小于0,则返回-1.如果整数大于0,则返回1.
不使用if/cond 解决此任务(允许的唯一特殊形式,定义,和,或)."
这是一项非常不切实际的任务,但仍然是我课程的要求.我已经坚持了几个小时这个任务,所以我喜欢一些输入!
请记住,该过程必须返回-1,0或1. #t或#f不够好.
这两个and和or是特殊版本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 ...))
Run Code Online (Sandbox Code Playgroud)
请注意,对于3个或更多元素,结果具有and或包含or在其中.你只需应用相同的转换,直到你有了一些东西if.
如果你想要这样的东西:
(if a 'x 'y)
Run Code Online (Sandbox Code Playgroud)
你看到它显然是(or (and a 'x) 'y)因为它变成了
(if (if a 'x #f)
(if a 'x #f)
'y)
Run Code Online (Sandbox Code Playgroud)
知道除了之外的每个值都#f被认为是真正的价值.在"反向"中执行此操作的基本方法是了解如何and和or短路if.如果您需要返回一个特殊值而不是您使用的谓词的结果,并且:
(and (null? x) 'empty-result)
Run Code Online (Sandbox Code Playgroud)
如果您需要一个false值来继续使用逻辑 or
(or (and (null? x) 'empty-result)
(and (pair? x) 'pair-result))
Run Code Online (Sandbox Code Playgroud)
如果您需要默认设置并且or只需添加它.
(or (and (null? x) 'empty-result)
(and (pair? x) 'pair-result)
'default-result)
Run Code Online (Sandbox Code Playgroud)
如果您碰巧and在外部,则需要包装or以获取默认结果:
(or (and ...)
'default-result)
Run Code Online (Sandbox Code Playgroud)
祝好运!