<aside> 💡 While writing functions processing two one-of types (e.g. 2 lists), drawing a cross product table can assist by visualising the possible paths the function could take (depending on the form each one-of type assumes).
</aside>
“What's going to happen in this video is, we're going to see that we can use the type comments to reason about the actual behavior of a function. We're going to take one more step towards designing a function based on a model of the function. What I mean by model is a more abstract representation of the function, or a less detailed representation of the function that tells us enough about what the function has to do that we can make some real design decisions based only on the model. In some sense, we're going to be programming using a picture before we're programming using code.”
prefix=?
, a function that processes 2 lists and returns true
if the 1st list lsta
is a prefix of the 2nd list lstb
.prefix=?
;; For this example:
;; Cases:
;; 1. both lists are empty
;; 2. lsta is not empty, but lstb is empty
;; 3. lstb is not empty, but lsta is empty
;; 4. both lists are non-empty
(define (prefix=? lsta lstb)
(cond [(and (empty? lsta)(empty? lstb)) true] ; case 1
[(and (cons? lsta)(empty? lstb)) false] ; case 2
[(and (empty? lsta)(cons? lstb)) true] ; case 3
[(and (cons? lsta)(cons? lstb))
(if (string=? (first lsta)(first lstb)) ; reference rule: (cons String ListOfString))
(prefix=? (rest lsta)(rest lstb)) ; self-reference rule: ListOfString is one of: empty, (cons String ListOfString)
false)])) ; case 4