In: Computer Science
Write a function lgrep that returns the “lines” within a list that contain a given sublist. Use the sublist function implemented in previous exercise to build lgrep.
> (lgrep ’(c d e) ’((a b c d e f g)
(c d c d e)
(a b c d)
(h i c d e k)
(x y z)))
((a b c d e f g) (c d c d e) (h i c d e k))
You may assume that all elements of (all lines of) all argument lists are atoms.
using scheme
Code:
;;EX: (sublist '(c d e) '(c d c d e)) returns #t
(define (sublist ls1 ls2)
(cond ((null? ls2) #f) ;;if second list empty returns false
((null? ls1) #t) ;;if first list is empty returns true
(else (sublist1 ls1 (check (car ls1) ls2)))))
;;Ex: (check '(c d e) '(c d c d e))returns ((c d c d e) (c d
e))
(define (check n list) ;;returns list strting with first element of
given sublist
(cond ((null? list) '())
((equal? n (car list)) (cons list (check n (cdr list))))
(else (check n (cdr list)))))
;;Ex:(sublist '(c d e) '((c d c d e) (c d e))) returns #t
(define (sublist1 ls1 ls2)
(cond ((null? ls2) #f)
((null? ls1) #t)
((equal? (sublist2 ls1 (car ls2)) #t) #t)
(else (sublist1 ls1 (cdr ls2)))))
;;Ex:(sublist '(c d e) '(c d c d e)) returns #t
(define (sublist2 ls1 ls2)
(cond ((null? ls2) #f) ;;if second list empty returns false
((null? ls1) #t) ;;if first list is empty returns true
((equal? (car ls1) (car ls2)) (sublist3 (cdr ls1) (cdr ls2))) ;;if
first element of list 1 equal to first element
;;check rest of the elements of list1 are contigeous subset of
list2
(else (sublist2 ls1 (cdr ls2))))) ;;else continue with rest of
list2
(define (sublist3 ls1 ls2) ;;HELPER_FUNCTION
(cond ((null? ls1) #t) ;;if second list empty returns false
((null? ls2) #f) ;;if first list is empty returns true
((equal? (car ls1) (car ls2)) (sublist3 (cdr ls1) (cdr ls2))) ;;if
first element of list 1 equal to first element check rest
elements
(else #f))) ;;else sublist is not contigeous, so returns
false.
;;MAIN_FUNCTION
(define (lgrep list1 list2)
(cond ((null? list2) '()) ;;If list is empty returns '()
((null? list1) list2);;if first list is empty returns 2nd
list
((equal? (sublist list1 (car list2)) #t) (cons (car list2) (lgrep
list1 (cdr list2))));;if sublist is equal then add it to it
(else (lgrep list1 (cdr list2))))) ;;else continue in rest of the
list
Snapshot of Code and Output:
Output: