Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

Scheme, search if a word is a part of list

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...