functions and lists in scheme/racket

2019-07-11 06:19发布

问题:

How would you define a function which takes one argument, which should be a list, and returns the elements in the list which are themselves lists?

(check-expect (find-sublists ’(1 2 () (3) (a b c) a b c)) 
              ’(() (3) (a b c)))

回答1:

Do you have experience designing functions that can filter through a list?

A simpler problem with the same flavor as the original is something like this: design a function that takes a list of numbers and keeps only the even numbers. Would you be able to do that function?

Looking at http://www.ccs.neu.edu/home/matthias/HtDP2e/htdp2e-part2.html and going through its guided exercises may also help.



回答2:

Two useful tools which should start you on your way:

1) Traversing through a list:

; traverse: takes a list of numbers
; Goes through each element, one-by-one, and alters it
(define traverse
  (lambda (the_list)
    (if (empty? the_list)
        empty
        (cons (+ 1 (first the_list)) 
              (traverse (rest the_list))))))

(traverse (cons 3 (cons 4 empty))) returns (cons 4 (cons 5 empty))

2) list?:

(list? (list 1 2 3)) returns #t
(list? 5) returns #f