[plt-scheme] HtDP Exercise 21.1.2

From: Roman Sykora (4rt.f15h at gmail.com)
Date: Thu Dec 10 08:55:35 EST 2009

Hi.

Continuing my Scheme studies using HtDP I encountered Ex. 21.1.2 where
I should define fold as abstraction of the two given functions:

;; sum : (listof number) -> number , and
;; product : (listof number) -> number.

After that I should define append in term of fold. Eventually I came
up with:

;; fold : (X Y -> Z) Z (listof X) -> Z
(define (fold f base lst)
  (cond ((empty? lst) base)
        (else (f (car lst) (fold f base (cdr lst))))))

;; sum : (listof number) -> number
(define (sum ln)
  (fold + 0 ln))

;; sum tests
(check-expect (sum '()) 0)
(check-expect (sum '(1 2 3 4 5)) 15)

;; product : (listof number) -> number
(define (product ln)
  (cond ((empty? ln) 0)
        (else (fold * 1 ln))))

;; product tests
(check-expect (product '()) 0)
(check-expect (product '(1 2 3 4 5)) 120)

;; my-append : list list -> list
(define (my-append l1 l2)
  (fold concat '() (list l1 l2)))

;; my-append tests
(check-expect (my-append '() '()) '())
(check-expect (my-append '(1) '()) '(1))
(check-expect (my-append '() '(2)) '(2))
(check-expect (my-append '(1 2) '(3 4)) '(1 2 3 4))
(check-expect (my-append '((1 2)) '((3 4))) '((1 2) (3 4)))

;; concat : list list -> list
(define (concat l1 l2)
  (cond ((empty? l2) l1)
        ((empty? l1) l2)
        ((empty? (cdr l1)) (cons (car l1) l2))
        (else (cons (car l1) (concat (cdr l1) l2)))))

;; concat tests
(check-expect (concat '() '()) '())
(check-expect (concat '(1) '()) '(1))
(check-expect (concat '() '(2)) '(2))
(check-expect (concat '(1 2) '(3 4)) '(1 2 3 4))
(check-expect (concat '((1 2)) '((3 4))) '((1 2) (3 4)))

What puzzles me is that  my-append and concat have the same contracts
and the same results. fold is not needed to define my-append.

I'm unsure whether my results are the expected results and wonder if
there is another solution to this exercise which I fail to see.

Thanks for your time.


Posted on the users mailing list.