;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-reader.ss" "lang")((modname 7astarter) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f))) ;; A [Keyed X] is a (list Number X) ;; and represents an X and its extracted "key" ;; A Movie is a (make-movie String Number) (define-struct movie [title runtime]) ;; and represents a movie's title and runtime in minutes ;; sort-by-title-length : [List-of Movie] -> [List-of Movie] ;; Sort the movies by their title's length (ascending) (define (sort-by-title-length lom) (local [;; insert-by-title-length : [Keyed Movie] [List-of [Keyed Movie]] -> [List-of [Keyed Movie]] ;; Find the correct spot for the title length (define (insert-by-title-length nm lonm) (cond [(empty? lonm) (list nm)] [(cons? lonm) (if (<= (first nm) (first (first lonm))) (cons nm lonm) (cons (first lonm) (insert-by-title-length nm (rest lonm))))]))] (map second (foldr insert-by-title-length '() (map list (map (compose string-length movie-title) lom) lom))))) (check-expect (sort-by-title-length (list (make-movie "Sorry To Bother You" 111) (make-movie "Hereditary" 127) (make-movie "Annihilation" 120) (make-movie "Blindspotting" 96) (make-movie "You Were Never Really Here" 95))) (list (make-movie "Hereditary" 127) (make-movie "Annihilation" 120) (make-movie "Blindspotting" 96) (make-movie "Sorry To Bother You" 111) (make-movie "You Were Never Really Here" 95))) ;; An [NEList-of X] (Non-Empty List of X) is one of: ;; - (cons X '())) ;; - (cons X [NEList-of X]) ;; sort-by-biggest : [List-of [NEList-of Number]] -> [List-of [NEList-of Number]] ;; Sort the lists by their biggest element (ascending) (define (sort-by-biggest lonelon) (local [;; A KNELoN is a [Keyed [NEList-of Number]]] ;; insert-by-biggest : KNELoN [List-of KNELoN] -> [List-of KNELoN] ;; Find the correct spot for the biggest number (define (insert-by-biggest nnelon lonnelon) (cond [(empty? lonnelon) (list nnelon)] [(cons? lonnelon) (if (<= (first nnelon) (first (first lonnelon))) (cons nnelon lonnelon) (cons (first lonnelon) (insert-by-biggest nnelon (rest lonnelon))))])) ;; biggest : [NEList-of Number] -> Number ;; Find the biggest number in the non-empty list of numbers (define (biggest nelon) (foldr max (first nelon) (rest nelon)))] (map second (foldr insert-by-biggest '() (map list (map biggest lonelon) lonelon))))) (check-expect (sort-by-biggest (list (list 6) (list 1 2 3) (list 5 6) (list 23))) (list (list 1 2 3) (list 6) (list 5 6) (list 23)))