Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Functional Programming / 05-Practice-03.11.2022.rkt
blob: 8e5fd7eafe385007a5252f80fd1dbaa733f05ed9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#lang racket

;;; Exercise 01

(define (list-len a)
  (if (null? a)
    0
    (add1 (list-len (cdr a)))))

;;; Exercise 02

(define (list-contains lst elem)
  (cond [(null? lst) #f]
        [(= (car lst) elem) #t]
        [else (list-contains (cdr lst) elem)]))

;;; Exercise 03

(define (list-insert lst elem ind)
  (if (= ind 0)
    (list* elem lst)
    (list* (car lst) (list-insert (cdr lst) elem (sub1 ind)))))

;;; Exercise 04

(define (list-min lst)
  (define (calc-iter lst minel)
    (cond [(null? lst) minel]
          [(< (car lst) minel) (calc-iter (cdr lst) (car lst))]
          [else (calc-iter (cdr lst) minel)]))
  (calc-iter lst (car lst)))

;;; Exercise 05

(define (remove-first lst elem)
  (if (= (car lst) elem)
    (cdr lst)
    (if (null? (cdr lst))
      lst
      (list* (car lst) (remove-first (cdr lst) elem)))))

;;; Exercise 06

(define (remove-elem lst elem)
  (if (null? lst)
    lst
    (if (= (car lst) elem)
      (remove-elem (cdr lst) elem)
      (list* (car lst) (remove-elem (cdr lst) elem)))))

;;; Exercise 07

(define (list-concat lst1 lst2)
  (if (null? lst1)
    lst2
    (if (null? (cdr lst1))
      (list* (car lst1) lst2)
      (list* (car lst1) (list-concat (cdr lst1) lst2)))))

;;; Exercise 08

(define (list-rev lst)
  (define (calc-iter toret lst)
    (if (null? lst)
      toret
      (calc-iter (list-insert toret (car lst) 0) (cdr lst))))
  (calc-iter '() lst))

;;; Exercise 09

(define (remove-duplicates subxs xs)
  (if (= (car xs) subxs)
    (list* (car xs) (remove-elem (cdr xs) subxs))
    (list* (car xs) (remove-duplicates subxs (cdr xs)))))

;;; Exercise 10

(define (sublist-between start end xs)
  (cond [(> start 0) (sublist-between (sub1 start) (sub1 end) (cdr xs))]
        [(> end 1) (list* (car xs) (sublist-between 0 (sub1 end) (cdr xs)))]
        [else (list (car xs))]))

;;; Exercise 11

(define (count-occurrences subxs xs)
  (define (calc-iter occs lst)
    (if (null? lst)
      occs
      (calc-iter (if (= (car lst) subxs) (add1 occs) occs)
                 (cdr lst))))
  (calc-iter 0 xs))