方案,搜索单词是否为列表的一部分 [英] Scheme, search if a word is a part of list

查看:70
本文介绍了方案,搜索单词是否为列表的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个程序,该程序正在搜索元素是否是列表的一部分,但是它不适用于单词 我的程序:

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

示例:

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

请帮助.

推荐答案

Scheme遇到(quote x)或它的缩写形式'x x时,结果是未评估的.因此,(quote ((quote three) (quote four) (quote five)))成为列表((quote three) (quote four) (quote five)).我认为您打算传递(quote (three four five)),您可以编写'(three four five),并且自从您搜索的内容是第一个元素以来,您的过程就可以正常工作.

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.

如果您搜索的元素不是lst中的第一个元素,则您有一个未绑定的变量会导致它不起作用,这是一个错误. x我猜应该实际上是绑定变量xs.我已经将每个xs重命名为x(因为xs通常表示一个列表,这里是一个搜索元素)

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

如果您确实想搜索符号以外的其他内容,则应使用equal?代替eq?,如下所示:

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

这篇关于方案,搜索单词是否为列表的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆