简体   繁体   中英

How to look for an element in a list of lists in racket

I'm trying to find an element in a list of lists and print the lists that contain that element.

For the test: (search-table '((1 2 3) (4 2) (3 3 4) (5 3 2 1)) 1), the output is:

'((1 2 3) (5 3 2 1))

This is my code in DrRacket so far:

(define (search-table table item)
  (if(equal? table null)
  '()
    (cons(search-table first table item))(search-table rest table item)))

But this code is giving me an error message which says:

if: bad syntax; has 4 parts after keyword in: (if (equal? table null) (quote ()) (cons (search-table first table item)) (search-table rest table item))

Please help me with this as I am very new to Racket.

If the value is a member of the list, cons the list onto the result

(define (search-table lists value)
  (cond ((null? lists) '())
        ((member value (car lists)) 
           (cons (car lists) (search-table (cdr lists) value)))
        (else (search-table (cdr lists) value))))

(search-table '((a b c d) (b c) (c d e f) (a b c)) 'a)
;; '((a b c d) (a b c))

You tagged this with tail-recursion tho, so let's do it with constant space

(define (search-table lists value)
  (let loop ((lists lists) (acc null))
    (cond ((null? lists) acc)
          ((member value (car lists)) 
             (loop (cdr lists) (cons (car lists) acc)))
          (else (loop (cdr lists) acc)))))

(search-table '((a b c d) (b c) (c d e f) (a b c)) 'a)
;; '((a b c) (a b c d))

But that result is in reverse order; according to your question anyway – we can "fix" that using a continuation as our accumulator instead of a list

(define (search-table lists value)
  (let loop ((lists lists) (acc identity))
    (cond ((null? lists)
           (acc null))
          ((member value (car lists))
           (loop (cdr lists) (lambda (rest)
                               (acc (cons (car lists) rest)))))
          (else
           (loop (cdr lists) acc)))))

(search-table '((a b c d) (b c) (c d e f) (a b c)) 'a)
;; '((a b c d) (a b c))

You tagged this with functional-programming tho, so let's do it using higher order functions

(define (search-table lists value)
  (filter (lambda (list) (member value list))
          lists))

(search-table '((a b c d) (b c) (c d e f) (a b c)) 'a)
;; '((a b c d) (a b c))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM