Reputation: 38
I am writing a function that finds the farthest left node in any tree. The function does not traverse the tree or give the farthest left node but just gives the left most child of the first node.
(define (far-left tree)
(cond (null? (cadr tree))
(car tree)
(far-left (cdr tree))))
sample input, which gives many nodes rather than the desired one:
(display (far-left '(1 (3 4 (6 7 (12 13))) 8 9 (10 11))))
Upvotes: 0
Views: 538
Reputation: 66371
What you call "the left most child of the first node" is (cadr tree)
.
There is one (cadr tree)
in your function, and that suggests that the first condition is always true.
And that is what's happening.
cond
's form is
(cond clause-1 clause-2 ...)
Each clause in turn has the form (condition value)
.
That is,
(cond (condition-1 value-1)
(condition-2 value-2)
(condition-3 value-3)
...)
If you match this to your function, you will see that
null?
is condition-1
and (cadr tree)
is value-1
,car
is condition-2
and tree
is value-2
, andfar-left
is condition-3
and (cdr tree)
is value-3
.Since null?
is not #f
, the first clause is always selected.
The correct form is
(define (far-left tree)
(cond
((null? (cadr tree)) (car tree))
(else (far-left (cdr tree)))
This code still does not work, though.
Fixing the bugs left as an exercise.
Upvotes: 3
Reputation: 2137
Data Definition: Tree
Tree
is either a Leaf
or a Node
where:
Leaf
is a Number
. Node
is a non-empty list of sub-Tree
s .Function: far-left
Leaf
as an input is invalid because we're supposed to find the "farthest left node in any tree.Node
has Leaf
as its left-most (or first
) element, then it is the left-most node. If the left-most element is a Tree
that is not a Leaf
we recur on it.#lang typed/racket
(define-type Leaf Number)
(define-type Node (Pairof Tree (Listof Tree)))
(define-type Tree (U Leaf Node))
(: far-left (-> Tree Node))
(define (far-left tree)
(cond [(number? tree) (error "Farthest left node of a leaf does not exist!")]
[(cons? tree) (if (number? (first tree)) tree (far-left (first tree)))]))
Tests:
(far-left '(1 (3 4 (6 7 (12 13))) 8 9 (10 11)))
; => '(1 (3 4 (6 7 (12 13))) 8 9 (10 11))
(far-left '((3 4 (6 7 (12 13))) 1 8 9 (10 11)))
; => '(3 4 (6 7 (12 13)))
(far-left '(((6 7 (12 13)) 3 4) 1 8 9 (10 11)))
; => '(6 7 (12 13))
(far-left '((((12 13) 6 7) 3 4) 1 8 9 (10 11)))
; => '(12 13)
Upvotes: 2