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))
b0
should return '()
(define b1 (addToTree b0 4 "4"))
b1
should return '(4 "4" () ())
(define b2 (addToTree b1 6 "6"))
b2
should return '(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...:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.