Scheme, search if a word is a part of list

允我心安 提交于 2019-12-12 03:27:13

问题


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.


回答1:


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



回答2:


In Scheme there really isn't a concept of 'words' - you've got symbols or strings. From what you've written your are looking to find symbols. Your code has a number of simple errors, here is a simple version:

(define (element? xs lst)
  (and (not (null? lst))
       (or (eq? xs (car lst))
           (element? xs (cdr lst)))))


> (element? 'three (list 'three 'four 'five))
#t

Note: Anytime you see cond returning values of #t or #f you might prefer rewriting in terms of and and or




回答3:


eq? tests if two objects are the same location in memory. It doesn't actually compare values. If you construct identical strings at two different memory locations, eq? returns false. Use string= instead.

I wanted to show some example code but Scheme is aggressively interning strings and I can't get two separately allocated identical strings to exist...

Relevant question



来源:https://stackoverflow.com/questions/19349749/scheme-search-if-a-word-is-a-part-of-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!