Skip to main content
added 8 characters in body; edited title
Source Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237

(scheme) [SICP ex. 2.61] adjoin Adjoin-set for an ordered set representation

From SICP:

Exercise 2.61. GiveExercise 2.61

Give an implementation of adjoin-set using the ordered representation. By analogy with element-of-set? show how to take advantage of the ordering to produce a procedure that requires on the average about half as many steps as with the unordered representation.

(define (adjoin-set x set)
  (define (rec subset) 
    (cond ((null? subset) (list x))
          ((> x (car subset)) (cons (car subset) (rec (cdr subset))))
          (else (cons x subset))))
  (if (element-of-set? x set)
      set
      (rec set)))

Can this be improved?

(scheme) [SICP ex. 2.61] adjoin-set for an ordered set representation

From SICP:

Exercise 2.61. Give an implementation of adjoin-set using the ordered representation. By analogy with element-of-set? show how to take advantage of the ordering to produce a procedure that requires on the average about half as many steps as with the unordered representation.

(define (adjoin-set x set)
  (define (rec subset) 
    (cond ((null? subset) (list x))
          ((> x (car subset)) (cons (car subset) (rec (cdr subset))))
          (else (cons x subset))))
  (if (element-of-set? x set)
      set
      (rec set)))

Can this be improved?

Adjoin-set for an ordered set representation

From SICP:

Exercise 2.61

Give an implementation of adjoin-set using the ordered representation. By analogy with element-of-set? show how to take advantage of the ordering to produce a procedure that requires on the average about half as many steps as with the unordered representation.

(define (adjoin-set x set)
  (define (rec subset) 
    (cond ((null? subset) (list x))
          ((> x (car subset)) (cons (car subset) (rec (cdr subset))))
          (else (cons x subset))))
  (if (element-of-set? x set)
      set
      (rec set)))

Can this be improved?

Tweeted twitter.com/#!/StackCodeReview/status/60900498085126144
Source Link
jaresty
  • 2.2k
  • 1
  • 25
  • 45

(scheme) [SICP ex. 2.61] adjoin-set for an ordered set representation

From SICP:

Exercise 2.61. Give an implementation of adjoin-set using the ordered representation. By analogy with element-of-set? show how to take advantage of the ordering to produce a procedure that requires on the average about half as many steps as with the unordered representation.

(define (adjoin-set x set)
  (define (rec subset) 
    (cond ((null? subset) (list x))
          ((> x (car subset)) (cons (car subset) (rec (cdr subset))))
          (else (cons x subset))))
  (if (element-of-set? x set)
      set
      (rec set)))

Can this be improved?