尝试创建不可变二进制搜索树 . 我从创建构造函数开始创建空列表,以及使用以下代码逐个添加元素到树的方法 .
#lang racket
(define (constructTree) '())
(define (addToTree Tree k v)
(cond [(null? Tree)
(cons Tree cons((cons k '()) v))]
[else
(cond [(>(car Tree) k)
(cons Tree cons((cons k '()) v))
]
[else
(cons Tree '() cons((cons k '()) v) )
]
)]
)
)
(define bst (addToTree (addToTree (addToTree (addToTree (constructTree)3 "3") 1 "1") 2 "2") 5 "5"))
bst
我的意思是不可变的是如果我打电话 (define b0 (constructTree))
b0
应该返回 '()
(define b1 (addToTree b0 4 "4"))
b1
应该返回 '(4 "4" () ())
(define b2 (addToTree b1 6 "6"))
b2
应该返回 '(4 "4" () (6 "6" () ()))
...等等 .
但我收到此错误: application: not a procedure; expected a procedure that can be applied to arguments given: '(3) arguments...:
任何线索为什么我得到这个错误或我做错了什么?先感谢您 .
1 回答
我想你可能正在寻找这样的东西:
请注意,由于不变性,每次都不需要构造新的空树 . 您只需为空列表创建
emptyTree
别名即可 .