Reputation: 23
Hi the problem is I want to see if a binary tree is N
We call binary trees, where N be the number of numbers that will contain the list of all nodes. For example this is a binary tree 2:
'((1 2) ((7 10) ((2 4) null null)) ((6 8) ((10 13) null null) null))
And this is a binary tree 1:
'(2- (7- (2 null null) (6 (5 null null) (11 null null))) (5 null (9 (4 null null) null)))
I have this code:
(define (abN? arbol N) (
cond
[(= (length (list-ref list 0)) N) "Arbol Binario N" "No es un arbol binario N" ]
[(= (number? (car list)) N) "Arbol Binario 1" "No es un arbol binario 1" ]
)
)
Then put this in the console:
(abN? '((1 2) ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 2)
and give me this error
car: contract violation
expected: pair?
given: #<procedure:list>
What I have been mistaken?
Thank you.
Upvotes: 0
Views: 1327
Reputation: 236004
There are several mistakes in your code, try this:
(define (abN? arbol N)
(cond
[(number? (car arbol))
(if (= N 1)
"Arbol Binario 1"
"No es un arbol binario 1")]
[(list? (car arbol))
(if (= (length (car arbol)) N)
"Arbol Binario N"
"No es un arbol binario N")]
[else (error "Dato de entrada incorrecto")]))
Explanation:
arbol
, but in your code you're referring to it as list
(which by the way, is a built-in function). This is what's causing the error reportedlist-ref
for accessing the first element of a list, use car
insteadcond
expression works. Each condition evaluates to the last value of the expressions that follow it, if you need to test for further conditions you have to use an if
or another cond
inside, you seem to believe that each condition has an implicit if-else
condition, and that's not correctIt works as expected for the possible inputs:
(abN? '(1 ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 1)
=> "Arbol Binario 1"
(abN? '(1 ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 2)
=> "No es un arbol binario 1"
(abN? '((1 2) ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 2)
=> "Arbol Binario N"
(abN? '((1 2) ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 3)
=> "No es un arbol binario N"
(abN? '("bogus" ( (7 10) ( (2 4) null null) ) ((6 8) ((10 13) null null) null)) 3)
=> Unknown input
Upvotes: 1