SICP – cap. 2 – abstraction barriers – esercizi – 4

best

Da qui oggi un esercizio, copiando qui.

Exercise 2.2.  Consider the problem of representing line segments in a plane. Each segment is represented as a pair of points: a starting point and an ending point. Define a constructor make-segment and selectors start-segment and end-segment that define the representation of segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors x-point and y-point that define this representation. Finally, using your selectors and constructors, define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint (the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures, you’ll need a way to print points:

(define (print-point p)
  (newline)
  (display "(")
  (display (x-point p))
  (display ",")
  (display (y-point p))
  (display ")"))

<mode nostalgia on> quando ero piccolo cose simili ne ho fatte parecchie, sigh 😊 <mode nostalgia off>. OK, vado.

;; point
(define (make-point x y)
  (cons x y))

(define (x-point point)
  (car point))  
  
(define (y-point point)
  (cdr point))

;; segment
(define (make-segment p1 p2)
  (list p1 p2))

(define (start-segment segment)
  (car segment))

(define (end-segment segment)
  (car (cdr segment)))
  
;; midpoint
(define (midpoint segment)
  (cons 
    (/ ( + 
      (car (start-segment segment))
      (car (end-segment segment))) 2)
    (/ (+
      (cdr (start-segment segment))
      (cdr (end-segment segment))) 2)))

;; print-point
(define (print-point p)
  (newline)
  (display "(")
  (display (x-point p))
  (display ",")
  (display (y-point p))
  (display ")"))

s147

La soluzione di Bill the Lizard è simile alla mia ma più sintetica, OK, lui è über.
Meno pulita quella di sicp-ex, usa variabili intermedie.
Bravo Spaceman Aki!

Solo io ho usato la procedura list, ma mi sembra che sia OK.

:mrgreen:

Annunci
Post a comment or leave a trackback: Trackback URL.

Trackbacks

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...

%d blogger hanno fatto clic su Mi Piace per questo: