Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #lang racket
- ;;; Empty list base-case. Use as a basis for 'prepend'
- (define (empty selector)
- (selector null null #t))
- ;;; Prepend : prepend given element to list. use 'empty' as basis
- (define (prepend element list)
- (lambda (selector)
- (selector element list #f)))
- ;;; Head : return first element in the list
- (define (head list)
- (list (lambda (head tail e) head)))
- ;;; Tail : return second element in the list, either a list, or null
- (define (tail list)
- (list (lambda (head tail e) tail)))
- ;;; empty? : return true if given list is empty
- (define (empty? list)
- (list (lambda (head tail e) e)))
- ;;; length : return length of given list
- (define (length list)
- (cond
- [(empty? list) 0]
- [else (+ 1 (length (tail list)))]))
- ;;; drop : return the list without the first n elements
- (define (drop list number)
- (cond
- [(= number 0) list]
- [else (drop (tail list) (- 1 number))]))
- ;;; take : return the list with only the first n elements
- (define (take list number)
- (cond
- [(= number 0) empty]
- [else (prepend (head list) (take (tail list) (- 1 number)))]))
- ;;; slice : retun the sub-list of a given start and end
- (define (slice list start end)
- (take (drop list start) (- end start)))
- ;;; get : retun the nth element of the list
- (define (get list number)
- (cond
- [(= 0 number) (head list)]
- [else (drop (tail list (- 1 number)))]))
- ;;; map : apply a function to each element of the list
- (define (map function list)
- (cond
- [(empty? list) list]
- [else (prepend (function (head list)) (map function (tail list)))]))
- ;;; filter : return a list containing elements only for which the given list returns true
- (define (filter function list)
- (cond
- [(empty? list) list]
- [(function (head list)) (prepend (head list) (filter function (tail list)))]
- [else (filter function (tail list))]))
- ;;; contains? : return true if list contains a given element
- (define (contains? element list)
- (cond
- [(empty? list) #f]
- [(= element (head list)) #t]
- [else (contains? element (tail list))]))
- ;;; containsAll? : return true if list contains all elements
- (define (containsAll? listA listB)
- (cond
- [(empty? listA) #t]
- [(contains? (head listA)) (containsAll? tail(listA) listB)]
- [else #f]))
- (define (subset? listA listB)
- (cond
- [(and (empty? listA) (>= (length listB) (length listA)))]
- [(contains? (head listA)) (subset? (tail listA) listB)]
- (define l (prepend 5 empty))
Advertisement
Add Comment
Please, Sign In to add comment