On this page:
Designing Abstractions
Before You Go...
8.15

Lab 6 Designing and Using Abstractions🔗

lab!

Purpose: This lab will give you practice using existing list abstractions.

Textbook references: Chapter 14: Similarities Everywhere, Chapter 15: Designing Abstractions, Chapter 16: Using Abstractions

Designing Abstractions🔗

Exercise 1 Design the function merge-layers, which, like the command in Photoshop, merges a number of image layers together into one image, by overlaying each image on top of all of the remaining. Any number of image layers is represented by a list of images. Here is some data to get started:
(define LST-TRI (cons (triangle 20 "solid" "green")
                      (cons (triangle 35 "solid" "red")
                            (cons (triangle 45 "solid" "orange")
                                  (cons (triangle 55 "solid" "blue") '())))))
; Using LST-TRI in our merge-layers function should output an image of a concentric
; set of triangles, much like a triangular bullseye.

Exercise 2 Consider the following function definitions:
; matching-x-posn : [List-of Posn] Number Posn -> Posn
; Find the first Posn in the list with the given x-coordinate or return the given Posn
; if no such position can be found
(check-expect (matching-x-posn '() 10 (make-posn 0 0)) (make-posn 0 0))
(check-expect
 (matching-x-posn
  (cons (make-posn 1 2) (cons (make-posn 3 4) '())) 3 (make-posn 5 6))
 (make-posn 3 4))
(define (matching-x-posn lop desired-x default)
  (cond [(empty? lop) default]
        [(cons? lop)
         (if (= (posn-x (first lop)) desired-x)
             (first lop)
             (matching-x-posn (rest lop) desired-x default))]))
 
; string-with-length : [List-of String] Nat -> String
; Returns the first String in the given list with the given length or "no such string" if no
; such string can be found
(check-expect (string-with-length '() 10) "no such string")
(check-expect (string-with-length (cons "hi" (cons "hello" (cons "aloha" '()))) 5) "hello")
(define (string-with-length los desired-length)
  (cond [(empty? los) "no such string"]
        [(cons? los)
         (if (= (string-length (first los)) desired-length)
             (first los)
             (string-with-length (rest los) desired-length))]))
Design the function find-first-match, which abstracts these two functions. Be sure to redefine matching-x-posn and string-with-length using your abstraction.

Before You Go...🔗

If you had trouble finishing any of the exercises in the lab or homework, or just feel like you’re struggling with any of the class material, please feel free to come to office hours and talk to a TA or tutor for additional assistance.