Running queries against a list of lists in Scheme

2019-03-05 12:55发布

问题:

I'm stuck in the middle of my project. I have a list of lists like:

'((a for apple) (b is book) (c in cat) (ronn live in NY))

Now I want to make a query in the form of a list and have it display the correct entry in my list of lists. For example, if I input '(a for what) or '(what in cat) it will display (a for apple) or (c in cat). If I input '(ronn live in where) it will show (ronn live in NY).

Can anyone help me solve this problem?

回答1:

How about running a filter routine across the list, and using a lambda object initialized with your query information that will then be applied to the list until it finds a match.

So for instance, you would have a lamda that would look something like

(define (filter-object query)
    (define (query-function list-input)
        ;;do something here for query function that will take the initialized
        ;;query and match it against the list-input to see if there's a match
        ;;it should return #t or #f
    )

    ;;the return of the filter-object is the query function
    query_function) 

;;my-filter-function is initialized with a specific query
(define my-filter-function (filter-object '(a for what)))

Now with the filter-object initialized, run a filter across your list

(define (filter filter-function list-of-lists)
    (cond ((eq? list-of-lists '()) '())
          ((filter-function (car list-of-lists))
           (cons (car list-of-lists)
              (filter filter-function (cdr list-of-lists)))
          (else (filter filter-function (cdr list-of-lists))))

(filter my-filter-function my-list)

This should return a one-element list of the matches (providing you aren't placing more than one copy in your list set.

Hope this helps,

Jason



回答2:

Structure and Interpretation of Computer Programs, Video Lectures by Hal Abelson and Gerald Jay Sussman

Lecture 4a, Pattern Matching and Rule-based Substitution