首页 文章

为什么这个函数在返回false时返回true?

提问于
浏览
0

所以,我有这个辅助函数,它检查列表和对列表之间是否存在自反关系 .

(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是否为空列表的部分也返回true,允许我的其他函数返回true . 我一直难以理解为什么它会在几小时内返回#t而不是#f . 请帮我弄清楚这是怎么回事 . 哦,我正在使用Dr.Racket版本6.12 .

EDIT: 更清楚,我希望函数返回#f时L是'() as a base case so that the function doesn' t需要再做递归 .

2 回答

  • 0

    你把 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? 的定义 - 我无法运行此代码进行测试 .

  • 4

    您已在 cond 中嵌套 if . 让我们重写你的代码som相同的东西:

    (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)))))
    

相关问题