Algebraic data types: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 580: | Line 580: | ||
{{trans|OCaml}} |
{{trans|OCaml}} |
||
< |
<lang racket> |
||
#lang racket |
|||
;; Using short names to make the code line up nicely |
|||
(struct |
(struct N (color left value right) #:prefab) |
||
(define (balance t) |
(define (balance t) |
||
(match t |
(match t |
||
[( |
[(N 'B (N 'R (N 'R a x b) y c) z d) (N 'R (N 'B a x b) y (N 'B c z d))] |
||
( |
[(N 'B (N 'R a x (N 'R b y c)) z d) (N 'R (N 'B a x b) y (N 'B c z d))] |
||
[( |
[(N 'B a x (N 'R (N 'R b y c) z d)) (N 'R (N 'B a x b) y (N 'B c z d))] |
||
( |
[(N 'B a x (N 'R b y (N 'R c z d))) (N 'R (N 'B a x b) y (N 'B c z d))] |
||
[(t-node 'black a x (t-node 'red (t-node 'red b y c) z d)) |
|||
(t-node 'red (t-node 'black a x b) y (t-node 'black c z d))] |
|||
[(t-node 'black a x (t-node 'red b y (t-node 'red c z d))) |
|||
(t-node 'red (t-node 'black a x b) y (t-node 'black c z d))] |
|||
[else t])) |
[else t])) |
||
Line 599: | Line 597: | ||
(define (ins t) |
(define (ins t) |
||
(match t |
(match t |
||
['empty ( |
['empty (N 'R 'empty x 'empty)] |
||
[( |
[(N c l v r) (cond [(< x v) (balance (N c (ins l) v r))] |
||
[(> x v) (balance (N c l v (ins r)))] |
|||
[else t])])) |
|||
(match (ins s) [(N _ l v r) (N 'B l v r)])) |
|||
(balance (t-node c a y (ins b)))] |
|||
(define (visualize t0) |
|||
[else t])])) |
|||
(let loop ([t t0] [last? #t] [indent '()]) |
|||
(match (ins s) |
|||
(define (I mid last) (cond [(eq? t t0) ""] [last? mid] [else last])) |
|||
(for-each display (reverse indent)) |
|||
(printf "~a~a[~a]\n" (I "\\-" "+-") (N-value t) (N-color t)) |
|||
(define subs (filter N? (list (N-left t) (N-right t)))) |
|||
(for ([s subs] [n (in-range (sub1 (length subs)) -1 -1)]) |
|||
(loop s (zero? n) (cons (I " " "| ") indent))))) |
|||
(visualize (for/fold ([t 'empty]) ([i 16]) (insert i t))) |
|||
</lang> |
|||
<pre> |
|||
7[B] |
|||
+-3[B] |
|||
| +-1[B] |
|||
| | +-0[B] |
|||
| | \-2[B] |
|||
| \-5[B] |
|||
| +-4[B] |
|||
| \-6[B] |
|||
\-11[B] |
|||
+-9[B] |
|||
| +-8[B] |
|||
| \-10[B] |
|||
\-13[B] |
|||
+-12[B] |
|||
\-14[B] |
|||
\-15[R] |
|||
</pre> |
|||
=={{header|Rascal}}== |
=={{header|Rascal}}== |