Add first exercises from subsection 2.3.3

This commit is contained in:
Petar Kapriš 2025-03-17 21:31:04 +01:00
parent 549a238bda
commit 57b8846963
4 changed files with 57 additions and 0 deletions

15
chapter-2/ex-2.59.scm Normal file
View file

@ -0,0 +1,15 @@
#lang sicp
(define (element-of-set? x set)
(cond ((null? set) false)
((equal? x (car set)) true)
(else (element-of-set? x (cdr set)))))
; we will simply adjoin elements of set1 to set2 if they are not there
; and drop them if they are there
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((element-of-set? (car set1) set2)
(union-set (cdr set1) set2))
(else (union-set (cdr set1) (cons (car set1) set2)))))

24
chapter-2/ex-2.60.scm Normal file
View file

@ -0,0 +1,24 @@
#lang sicp
; element-of-set? is the exact same
; O(n)
(define (element-of-set? x set)
(cond ((null? set) false)
((equal? x (car set)) true)
(else (element-of-set? x (cdr set)))))
; O(1)
(define (adjoin-set x set)
(cons x set)) ; we don't have to check anymore
; O(n), where n is the length of set1
(define (union-set set1 set2)
(append set1 set2))
; intersection-set can still be the exact same
; O(n^2)
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1) (intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))

7
chapter-2/ex-2.61.scm Normal file
View file

@ -0,0 +1,7 @@
#lang sicp
(define (adjoin-set x set)
(cond ((null? set) (list x))
((< x (car set)) (cons x set))
((= x (car set)) set)
((> x (car set)) (cons (car set) (adjoin-set x (cdr set))))))

11
chapter-2/ex-2.62.scm Normal file
View file

@ -0,0 +1,11 @@
#lang sicp
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((< (car set1) (car set2)) (cons (car set1)
(union-set (cdr set1) set2)))
((= (car set1) (car set2)) (cons (car set1)
(union-set (cdr set1) (cdr set2))))
((> (car set1) (car set2)) (cons (car set2)
(union-set set1 (cdr set2))))))