英文:
How can cond from Racket be written using only logcal operators?
问题
为了我的作业,我需要编写一个递归函数,不使用任何条件语句,只使用逻辑运算符,但我不知道如何只使用逻辑运算符来编写条件语句。有人可以帮助吗?
作为参考,我使用 if 和 cond 编写了以下代码来创建我的函数:
(define (is-preferred? pref-list x y)
(if (null? pref-list)
#t
(cond
((equal? (car pref-list) x) #t)
((equal? (car pref-list) y) #f)
(else (is-preferred? (cdr pref-list) x y))
)
)
)
我尝试使用只有逻辑运算符来编写它,但它对所有情况都不起作用:
(define (is-preferred? pref-list x y)
(or (null? pref-list)
(or (equal? (car pref-list) x)
(and (equal? (car pref-list) y)
(is-preferred? (cdr pref-list) x y)
)
)
)
)
英文:
For my homework, I need to write a recursive function without any conditional statements, only logical operators and I don't have any idea how to write cond using only logical operators. Can someone help?
For reference I wrote this code for my function using if and cond:
(define (is-preferred? pref-list x y)
(if (null? pref-list)
#t
(cond
((equal? (car pref-list) x) #t)
((equal? (car pref-list) y) #f)
(else (is-preferred? (cdr pref-list) x y))
)
)
)
And I tried to write it using only logical operators and it doesn't work for all cases:
(define (is-preferred? pref-list x y)
(or (null? pref-list)
(or (equal? (car pref-list) x)
(and (equal? (car pref-list) y)
(is-preferred? (cdr pref-list) x y)
)
)
)
)
答案1
得分: 2
尝试这个 - 请注意我将结束括号放在一行上:
(define (is-preferred? pref-list x y)
(or (null? pref-list)
(equal? (car pref-list) x)
(and (not (equal? (car pref-list) y))
(is-preferred? (cdr pref-list) x y))))
英文:
Try this - note that I placed ending parentheses on one line:
(define (is-preferred? pref-list x y)
(or (null? pref-list)
(equal? (car pref-list) x)
(and (not (equal? (car pref-list) y))
(is-preferred? (cdr pref-list) x y))))
答案2
得分: 0
思考一下你的条件和结果。
然后你会看到,当且仅当以下条件成立时,结果为#t
:
(null? pref-list)
为#t
,或(equal? (car pref-list) x)
为#t
,或(not (equal? (car pref-list) y))
为#t
且(is-preferred? (cdr pref-list) x y)
为#t
。
然后将其翻译成Racket代码。
英文:
Think about your conditions and the result for a while.
Then you will see that the result is #t
if and only if
(null? pref-list)
is#t
, or(equal? (car pref-list) x)
is#t
, or(not (equal? (car pref-list) y))
is#t
and(is-preferred? (cdr pref-list) x y)
is#t
.
Then translate into Racket.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论