Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I did a program which is searching if an element is a part of the list, but it is not working with words My program:

(define (element? xs lst) 
  (cond ((null? lst) #f) 
        ((eq? xs (car lst)) #t) 
        (#t (element? x (cdr lst)))))

examples:

>(element? 'three (quote ((quote three) (quote four) (quote five))))
>,=> #f but i need #t 

please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

When Scheme encounters a (quote x) or it's short form 'x x is the result unevaluated. Thus (quote ((quote three) (quote four) (quote five))) becomes the list ((quote three) (quote four) (quote five)). I think you meant to pass (quote (three four five)), which you could write '(three four five) and your procedure would have worked since what you were searching for were the first element.

There is an error that you have an unbound variable making it not work if the searched element is not the first element in lst. x which I guess should actually be the bound variable xs. I've renamed every xs to x (since xs usually means a list and here it's a search element)

(define (element? x lst) 
  (cond ((null? lst) #f) 
        ((eq? x (car lst)) #t) 
        (else (element? x (cdr lst)))))

(element? 'c '(a b c d e f)) ; ==> #t
(element? 'g '(a b c d e f)) ; ==> #f
(element? (quote e) (quote (a b c d e))) ; ==> #t

If you really wanted to search for other things than symbols, you should use equal? in place of eq?, like this:

(define (element? x lst) 
  (cond ((null? lst) #f) 
        ((equal? x (car lst)) #t) 
        (else (element? x (cdr lst)))))

(element? '(hello dolly) '((hello paul) (hello dolly) (hello todd))) ; ==> #t

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...