;; lists.scm Daniel Azus ;; Theses are some helpful functions that deal with lists ;; Included function descriptions: ;; size: Returns the length of a list ;; last: Returns the last element in a list ;; SetElement: Changes the value at the given index in a list (changes 1st if index < 0, last element if Index > list size) ;; Find: Finds the first value's index that matches the value given ;; ChopListA: Chops all element off of the list after and including the index given ;; ChopListB: Chops all element off of the list before and including the index given ;; Checks the size of a list (length function does the same thing) (define (size alist) (cond [(empty? alist) 0] [else (+ 1 (size (rest alist)))] ) ) ;; Gets the last element in a list (define (last alist) (GetElement alist (size alist))) ;; Gets a specified element in a list (define (GetElement AList Index) (cond [(empty? AList) empty] [(< Index 1) empty] [(= Index 1) (first AList)] [else (GetElement (rest AList) (- Index 1))] ) ) ;; Helps SetElement add the 2 lists together (define (SetElementHelper AList1 List1Size AList2) (cond [(empty? AList1) AList2] [(< List1Size 1) AList2] [else (SetElementHelper AList1 (- List1Size 1) (cons (GetElement AList1 List1Size) AList2))] ) ) ;; Sets the given index in a list to the value given (define (SetElement AList Index Value) (cond [(empty? AList) AList] [(<= Index 1) (cons Value (ChopListB AList 1))] [else (SetElementHelper (ChopListA AList Index) (size (ChopListA AList Index)) (cons Value (ChopListB AList Index)) ) ] ) ) ;; Helps find a specified value in a list (define (FindHelper AList Value Index) (cond [(empty? AList) 0] [(eqv? (first AList) Value) Index] [else (FindHelper (rest AList) Value (+ Index 1))] ) ) ;; Finds a specified value in a list ;; Used to pass the initial index of 1 to the helper function (define (Find AList Value) (FindHelper AList Value 1) ) ;; Chops off all elements after and including the AfterThis value ;; It should be called by ChopListA (define (ChopListAHelper AList AfterThis SoFar) (cond [(empty? AList) empty] [(< AfterThis 1) empty] [(= AfterThis 1) empty] [else (cons SoFar (ChopListAHelper (rest AList) (- AfterThis 1) (first AList)))] ) ) ;; Chops off all elements after and including the AfterThis value (define (ChopListA AList AfterThis) (cond [(empty? AList) empty] [(< AfterThis 1) empty] [(= AfterThis 1) (rest AList)] [else (ChopListAHelper (rest AList) (- AfterThis 0) (first AList))] ) ) ;; Chops off all elements before and including the BeforeThis value (define (ChopListB AList BeforeThis) (cond [(empty? AList) empty] [(< BeforeThis 1) empty] [(= BeforeThis 1) (rest AList)] [else (ChopListB (rest AList) (- BeforeThis 1))] ) )