Skip to content

Instantly share code, notes, and snippets.

@jswrenn
Created August 23, 2013 19:22
Show Gist options
  • Save jswrenn/6323008 to your computer and use it in GitHub Desktop.
Save jswrenn/6323008 to your computer and use it in GitHub Desktop.
#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]))
;; Example. Defines 'l' to be a list containing 5
(define l (prepend 5 empty))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment