Created
March 7, 2021 18:01
-
-
Save sorawee/dd5f55cdbf210f837d2e61d6942941a8 to your computer and use it in GitHub Desktop.
tree-path.rkt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
;; tree-path :: tree? -> any/c -> (listof (or/c 'here 'left 'right)) | |
(define (tree-path t elt) | |
(let loop ([t t] [out '()]) | |
(match t | |
['empty '()] | |
[`(node ,(== elt) ,_ ,_) (reverse (cons 'here out))] | |
[`(node ,_ ,l ,r) | |
(match (loop l (cons 'left out)) | |
['() (loop r (cons 'right out))] | |
[left-result left-result])]))) | |
(module+ test | |
(require rackunit) | |
(check-equal? (tree-path 'empty 1) '()) | |
(check-equal? (tree-path '(node 1 empty empty) 1) '(here)) | |
(check-equal? (tree-path '(node 1 empty empty) 2) '()) | |
(check-equal? (tree-path '(node 2 (node 1 empty empty) empty) 1) | |
'(left here)) | |
(check-equal? (tree-path '(node 2 empty (node 1 empty empty)) 1) | |
'(right here)) | |
(check-equal? (tree-path '(node 2 (node 1 empty empty) (node 1 empty empty)) 1) | |
'(left here))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment