copy-list.scm 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. (define (mfilter p l)
  2. (cond ((null? l) '())
  3. ((p (car l))
  4. (cons (car l) (mfilter p (cdr l))))
  5. (else (mfilter p (cdr l)))))
  6. (define (mfilter p l)
  7. (cond ((null? l) '())
  8. ((p (car l))
  9. (cons (car l) (mfilter p (cdr l))))
  10. (else (mfilter p (cdr l)))))
  11. ;; '(define (reverse l)
  12. ;; (cond ((null? l) '())
  13. (define (copy l)
  14. "copies the list l"
  15. (if (null? l)
  16. '()
  17. (cons (car l) (copy (cdr l)))))
  18. "
  19. to copy a list l
  20. we make a fresh cons that contains the head of l, and the copy of the tail of l.
  21. if l is empty, the copy of l is '()
  22. ^- fully describing the algorithm. Except we don't know yet whether `copy` works--since we haven't proven *before* that it works/exists, wer're doing that right now. We need to show that the above description is also complete from a coverage standpoint: does that cover all possible lengths of lists?
  23. Can we show, that the use of `copy` will be less work, or in other words, *converge* towards a trivially solvable( or defined) case?
  24. The process that's gonna happen will then only encounter cases that we have defined above.
  25. So by logical deduction we know that the program will always work and give the right result.
  26. "
  27. (define (reverse-append l l2)
  28. "copies the list l in reverse order, but adds l2 on the right
  29. (y z) (x) -> (z y x)
  30. () (x) -> (x)
  31. (z) (y x) -> (z y x)
  32. l l2
  33. "
  34. (if (null? l)
  35. l2 ;; (begin (repl) l2)
  36. (reverse-append (rest l) (cons (first l) l2))))
  37. "
  38. reverse-append of the empty l is just l2 (nothing to be done).
  39. reverse-append of a non-empty l is
  40. the reverse of the rest of l, prepended to the first of l prepended to l2.
  41. We cover all the cases:
  42. - empty l
  43. - non-empty l: since the recursive call is done with a shorter l it will hit the empty l case and is defined for non-empty case, thus,
  44. reverse-append is defined for *all* lengths of l.
  45. And it doesn't matter how long l2 is since we only ever add to it.
  46. "
  47. (define (reverse l)
  48. "copies the list l in reverse order"
  49. (reverse-append l '())))
  50. ;; (append (reverse l) l2)
  51. ;; (append-reverse l l2)