[英]create binary search tree in racket?
try to create immutable binary search tree. 尝试创建不可变的二进制搜索树。 i started by create constructor to create empty list, and method to add element to tree one by one using the following code.
我从创建构造函数开始创建空列表,然后使用以下代码将元素一一添加到树中。
#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
what i mean by immutable is if i call (define b0 (constructTree))
我所说的不可变是指如果我调用
(define b0 (constructTree))
b0
should return '()
b0
应该返回'()
(define b1 (addToTree b0 4 "4"))
b1
should return '(4 "4" () ())
b1
应该返回'(4 "4" () ())
(define b2 (addToTree b1 6 "6"))
b2
should return '(4 "4" () (6 "6" () ()))
b2
应该返回'(4 "4" () (6 "6" () ()))
...etc. ...等等。
but i am getting this error: application: not a procedure; 但我收到此错误: 应用程序:不是过程; expected a procedure that can be applied to arguments given: '(3) arguments...:
预期可以应用于给定参数的过程:'(3)arguments ...:
any clue why i am getting this error or what i am doing wrong? 任何提示我为什么会收到此错误或我做错了什么? thank you in advance.
先感谢您。
I think you may be looking for something like this: 我认为您可能正在寻找这样的东西:
(define emptyTree '())
(define (addToTree Tree k v)
(match Tree
['()
(list k v '() '())]
[(list key val left right)
(if (> k key)
(list key val left (addToTree right k v))
(list key val (addToTree left k v) right))]))
Note that because of immutability, there's no need to construct a new empty tree each time. 请注意,由于具有不变性,因此无需每次都构造一个新的空树。 You can just make
emptyTree
an alias for the empty list. 您可以将
emptyTree
用作空列表的别名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.