Implementing has-list in scheme

对着背影说爱祢 提交于 2019-12-11 04:14:27

问题


how can you implement a Scheme function has-list recursively, which tests whether a list contains other list as an element. For example (has-list '(1 2 3)) should return false, and (has-list '(1 2 (3 4) 5)) should return true.


回答1:


If your implementation has something like ormap, then:

(define (has-list? l) (ormap list? l))

Using or as in Dan D.'s answer will not work.




回答2:


A list has a list as an element iff it is not the empty list and either its first element is a list or the rest of the list has a list as an element. The translation to Scheme code is left as an exercise for the reader.




回答3:


If you need to do it recursively and without using map:

 (define (has-list? lst)
    (cond
      ((null? lst) #f)
      ((list? (car lst)) #t)
      (else (has-list? (cdr lst)))))



回答4:


(define (has-list? X) (apply or (map list? X)))


来源:https://stackoverflow.com/questions/5135989/implementing-has-list-in-scheme

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