简体   繁体   English

如何在球拍列表中查找元素

[英]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:对于测试:(search-table '((1 2 3) (4 2) (3 3 4) (5 3 2 1)) 1),输出为:

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

This is my code in DrRacket so far:到目前为止,这是我在 DrRacket 中的代码:

(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))关键字 in 后有 4 个部分:(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.请帮我解决这个问题,因为我对 Racket 很陌生。

If the value is a member of the list, cons the list onto the result如果该值是一个member列表的, cons列表到结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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