Mek
Mek

Reputation: 1

Empty and '() in function not equal

i am learning racket for my course and while going through solutions to an assignment, I found that a function doesn't return true, when comparing empty and '()

Here is the output I'm getting:

(lst-contains? '(1 2 3 ()) '())      ; output: #t
(lst-contains? '(1 2 3 ()) empty)    ; output: #t
(lst-contains? '(1 2 3 empty) empty) ; output: #f (unexpected!)
(lst-contains? '(1 2 3 empty) '())   ; output: #f (unexpected!)

Here's my definition of lst-contains?:

(define (lst-contains? lst element)
  (cond
    [(empty? lst) #f]
    [(equal? (first lst) (element)) #t]
    [else (lst-contains? (rest lst) element)]))

Thanks : )

Upvotes: 0

Views: 153

Answers (2)

MLavrentyev
MLavrentyev

Reputation: 1969

This is due to the fact that quote (or ') "distributes" across a list. So, when you write '(1 2 3 empty), you're actually creating something that's equivalent to (list 1 2 3 'empty) not (list 1 2 3 empty).

You can check for yourself that this is the case by looking at the result of:

(list-ref '(1 2 3 empty) 3)      ; output: 'empty
(list-ref (list 1 2 3 empty) 3)  ; output: '()

Upvotes: 2

Renzo
Renzo

Reputation: 27424

In racket they are equal:

(define (lst-contains lst element)
  (cond
    ((empty? lst) #f)
    ((equal? (first lst) element) #t)
    (else (lst-contains (rest lst) element))))

(lst-contains '(1 2 3 ()) empty) ; -> #t

Tested in DrRacket.

Note that '(1 2 3 empty) is different from '(1 2 3 ()) since in the first case empty is taken as a symbol.

Upvotes: 0

Related Questions