如何使用仅逻辑运算符在Racket中编写cond?

huangapple go评论51阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月3日 20:00:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定