Home > Enterprise >  finding nodes at depth N in a tree with racket
finding nodes at depth N in a tree with racket

Time:01-20

I've written a piece of code which returns the nodes which are at depth N of a tree. The root is considered to be at depth 1.

#lang racket

(define (depth n tree) (
                    cond [(= n 1) (car tree)]
                         [(> n 1) (
                                   cond [(and (null? (cadr tree)) (null? (caddr tree)))
                                         (null)]
          
                                        [(and (not (null? (cadr tree))) (null? (caddr tree))) 
                                         (cons (depth (- n 1) (cadr tree)) null)]
         
                                        [(and (null? (cadr tree)) (not (null? (caddr tree)))) 
                                         (cons (depth (- n 1) (caddr tree)) null)]
         
                                        [(and (not (null? (cadr tree))) (not (null? (caddr tree))))
                                         (cons (depth (- n 1) (cadr tree)) (depth (- n 1) (caddr tree)))]
                                        )]
                         )
  )

Which works fine for depth 1, 2 and 3.

(define sampleTree
  `(A 
    (B 
     (D () ())
     (E () ())
     )
    (C
     ()
     (F
      (G () ())
      ()
      )
     )
    )
  )

(depth 1 sampleTree)
(depth 2 sampleTree)
(depth 3 sampleTree)

gives

'A
'(B . C)
'((D . E) F)

But for some reason, this does not work for depth 4.

(depth 4 sampleTree)
 application: not a procedure;
  expected a procedure that can be applied to arguments
  given: '()

I honestly have no idea why this happens. It seems like the null in the first branch of > n 1 is getting applied to something.

Any help on debugging this code is appreciated.

CodePudding user response:

The problem is (null). null is bound to the value '(). Putting parentheses around it tries to apply it as a procedure.

> null
'()
> (null)
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: '()
 [,bt for context]

May I suggest the following code formatting:

(define (depth n tree)
  (cond
   [(= n 1) (car tree)]
   [(> n 1)
    (cond
     [(and (null? (cadr tree)) (null? (caddr tree))) '()]
     [(and (not (null? (cadr tree))) (null? (caddr tree)))
      (cons (depth (- n 1) (cadr tree)) null)]
     [(and (null? (cadr tree)) (not (null? (caddr tree))))
      (cons (depth (- n 1) (caddr tree)) null)]
     [(and (not (null? (cadr tree))) (not (null? (caddr tree))))
      (cons (depth (- n 1) (cadr tree)) (depth (- n 1) (caddr tree)))])]))

You may also want to ask yourself what type of value depth should return. In your example output, 'A is a symbol, '(B . C) is a pair, and '((D . E) F) is a proper list (with a pair as the first element).

  • Related