Scheme Tree Puzzle: Expressing an Empty Node in a Final Pair -


i trying solve puzzle crawls binary tree in order find if specific value exists node. having issue evaluating pair looks '(1 '()). think when evaluate (= 4 '()) returns true incorrect obviously.

i attempted removing cons adds empty pair, getting following: (#f . #f) believe not pair. i'm having block on how build list of pairs via cons.

my code below:

my home made any? function

(define (any? f lst) (not (null? (filter f lst)))) 

version cons '():

(define value-exist?    (lambda (n xs)     (if (null? xs)          '()         (letrec ((node-left (car xs))                  (node-right (cdr xs))                  (true? (lambda (x) x)))           (if (list? node-left)                (any? true? (cons (value-exist? n node-left)                                  (cons (value-exist? n node-right)                                        '())))               (any? true? (cons (= n node-left)                                  (cons (value-exist? n node-right)                                        '())))))))) 

version have removed cons '():

(define value-exist?    (lambda (n xs)     (if (null? xs)          '()         (letrec ((node-left (car xs))                  (node-right (cdr xs))                  (true? (lambda (x) x)))           (if (list? node-left)              (any? true? (cons (value-exist? n node-left)                                (value-exist? n node-right)))             (any? true? (cons (= n node-left)                                (value-exist? n node-right)))                               ))))) 

sample call:

(value-exist? 4 '(1 2 3 (3 2 3))) 

your code not follow solution template recursively traversing list of lists (neither sample input nor procedures seem deal actual binary tree), it'd pointless trying fix current solution. instead i'll show correct recipe apply:

(define (value-exist? n xs)   (cond ((null? xs) ; check if list empty          #f)        ; if it's empty, didn't find looking         ((not (pair? xs)) ; check if current element not list          (equal? n xs))   ; if it's not list, check if it's element         (else                              ; otherwise          (or (value-exist? n (car xs))     ; advance recursion on car part              (value-exist? n (cdr xs)))))) ; advance recursion on cdr part 

it works expected:

(value-exist? 4 '(1 2 3 (3 2 3))) => #f  (value-exist? 4 '(1 2 3 (3 4 3))) => #t 

Comments