为什么该函数在应返回false时返回true?

时间:2018-07-20 06:15:25

标签: functional-programming racket

所以,我有这个帮助函数,用于检查列表和成对列表之间是否存在自反关系。

(define helper
  (lambda (L S)
    (cond
      ((if (equal? L '()) #f ;; here, when L equals empty list, it should return #f, but somehow it returns #t even if L is '().
          (if (equal? S (car (car L)))
              (if (list-equal? (car L))#t
                  (helper (cdr L) S))
              (helper (cdr L) S))))
          )))

但是,即使L是一个空列表,它检查L是否为空列表的部分也返回true,这使我的其他函数返回true。 我一直在试图找出为什么它在数小时内返回#t而不是#f的原因。请帮助我找出造成这种情况的原因。 哦,我正在使用Dr.Racket 6.12版。

编辑:更清楚地讲,我希望当L为'()时,该函数返回#f作为基本情况,以便该函数不再需要递归。

2 个答案:

答案 0 :(得分:4)

您将if表单放在cond内,这是多余的。 因此,您的错误肯定是您缺乏对cond语法的理解。 请记住cond语法如下:

(cond (condition1 what-to-do-if-condition1-is-true)
      (condition2 what-to-do-if-condition2-is-true)
      ( ...       ...                             )
      (else what-to-do-if-none-of-the-conditions-listed-above-evaluated-to-true))

因此,我根据以下内容形成了您的表情

(define helper
  (lambda (L S)
    (cond ((equal? L '()) #f)
          ((and (equal? S (car (car L))) (list-equal? (car L))) #t)
          (else (helper (cdr L) S)))))

由于您未提供list-equal?的定义-我无法运行此代码进行测试。

答案 1 :(得分:0)

您已将if嵌套在cond中。让我们用相同的代码重写代码:

(define helper
  (lambda (L S)
    (let ((result
           (if (equal? L '())
               #f
               (if (equal? S (car (car L)))
                   (if (list-equal? (car L))
                       #t
                       (helper (cdr L) S))
                   (helper (cdr L) S)))))
      (cond
        (result result)
        (else 'implementation-defined-value)))))

cond将返回一个实现定义的值,因为如果没有前面的谓词命中,则else子句。由于您的基本casse返回#f,因此它将使用默认的else大小写。

由于另一个答案显示的是cond代码,因此if与此相同:

(define helper
  (lambda (L S)
    (if (equal? L '())
        #f 
        (if (and (equal? S (car (car L)))
                 (list-equal? (car L)))
            #t
            (helper (cdr L) S)))))

您也只能用andor来写:

(define helper
  (lambda (L S)
    (and (pair? L)
         (or (and (equal? S (car (car L)))
                  (list-equal? (car L)))
             (helper (cdr L) S)))))