-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary-trees-from-structs.rkt
80 lines (65 loc) · 2.13 KB
/
binary-trees-from-structs.rkt
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
#lang racket
;;; File:
;;; binary-trees-from-structs.rkt
;;; Summary:
;;; Binary trees implemented as Racket structs.
;;; Author:
;;; Samuel A. Rebelsky
(require csc151/hop)
(require racket/match)
(require racket/include)
(provide (all-defined-out))
; +-----------------------------+------------------------------------
; | Binary tree node structures |
; +-----------------------------+
(struct binary-tree-node (top left right)
#:transparent
#:reflection-name 'binary-tree
#:guard
(lambda (top left right name)
(cond
[(not (binary-tree? left))
(error "binary-tree: Expects a binary tree as second parameter, received"
left)]
[(not (binary-tree? right))
(error "binary-tree: Expects a binary tree as third parameter, received"
right)]
[else
(values top left right)])))
; +-----------------------+------------------------------------------
; | Empty tree structures |
; +-----------------------+
(struct empty-tree ()
#:transparent)
; +--------------------+---------------------------------------------
; | Primary Procedures |
; +--------------------+
;;; (binary-tree value left right) -> binary-tree?
;;; value : any?
;;; left: binary-tree?
;;; right: binary-tree?
;;; Build a new binary tree.
(define binary-tree binary-tree-node)
;;; (binary-tree val) -> boolean?
;;; val : any?
;;; Returns true iff val is a binary tree.
(define binary-tree?
(lambda (val)
(or (empty-tree? val)
(binary-tree-node? val))))
;;; (binary-tree-top t) -> any
;;; t : tree?, (not (empty-tree? t))
;;; Returns the value at the root of this tree.
(define binary-tree-top binary-tree-node-top)
;;; (binary-tree-left t) -> any
;;; t : tree?, (not (empty-tree? t))
;;; Returns the left child of this tree.
(define binary-tree-left binary-tree-node-left)
;;; (binary-tree-right t) -> any
;;; t : tree?, (not (empty-tree? t))
;;; Returns the right child of this tree.
(define binary-tree-right binary-tree-node-right)
; +-------------+----------------------------------------------------
; | Common code |
; +-------------+
(include "includes/binary-trees-common.inc")