Binary Search Tree Scheme - insert

My friend and I are currently working on creating a Binary Search Tree in Scheme. We cannot get it to save what we have inserted. My professor said we are to use set-car! (cdr ( for the left subtree somehow, but I don't know where exactly to put it in. We are supposed to use set-car! (cddr ( for the right subtree also.
We have done all of this so far correctly, but we just need help making it save our inserted nodes.
Code:
(define make-empty-BST '())
;create function to see if BST is empty
(define (emptyBST? BST) (null? BST))
;make non-empty BST with explicit list implementation
(define (make-BST root left-subtree right-subtree)
(list root left-subtree right-subtree))
;helper get root function
(define (getRoot BST) (car BST))
;helper get left subtree function
(define (getLeftsubTree BST) (cadr BST)) ;(car (cdr tr))
;helper get right subtree function
(define (getRightsubTree BST) (caddr BST)) ;(car (cdr (cdr tr)))
;Checks to see if a leaf is empty
(define (emptyleaf? BST) (and (null? (getLeftsubTree BST)) (null? (getRightsubTree BST))))
;inserts an item into the BST
(define (BST-insert BST item)
(cond
((emptyBST? BST) ;if empty, create a new root with given item - use empty lists for left and right subtrees
(make-BST item make-empty-BST make-empty-BST))
((< item (getRoot BST)) ;if item less than root, add to left subtree
(make-BST (getRoot BST)
(BST-insert (getLeftsubTree BST) item) ;recursion
(getRightsubTree BST)))
((> item (getRoot BST))
(make-BST (getRoot BST)
(getLeftsubTree BST)
(BST-insert (getRightsubTree BST) item)))
(else BST))) ; it's already in BST, do nothing

Since this sounds like an assignment, I don't want to provide the exact code that you need, but I'll show two functions that could be said to replace the nth element of list. The first will be analogous to yours, in that it returns a new list and doesn't modify the input list. The second will modify the input list.
(define (replace-nth n element list)
;; return a new list like list, but whose
;; nth element is element
(if (= n 0)
(cons element (cdr list))
(cons (car list) (replace-nth (- n 1) element (cdr list)))))
(let ((l (list 1 2 3 4 5 6)))
(display (replace-nth 3 'x l)) ; prints (1 2 3 x 5 6)
(display l)) ; prints (1 2 3 4 5 6)
The first returns a new list, but doesn't modify the input list. It creates a new list using cons applied to part of the old list and some new value. This is similar to what you're doing when you insert by creating a new tree that has the new value. The tree that you've passed in won't have it, but the tree will.
(define (set-nth! n element list)
;; set the nth element of list to be element
(if (= n 0)
(set-car! list element)
(set-nth! (- n 1) element (cdr list))))
(let ((l (list 1 2 3 4 5 6)))
(display (set-nth! 4 'x l)) ; prints #<void>
(display l)) ; prints (1 2 3 4 x 6)
The second modifies the list that is passed to it. Its return value isn't quite so important, because the structure passed into it actually gets modified. This is more like what you'd want to do with your insert function. You need to recurse until you get to the correct node in the tree, and the set its left or right child to be a new tree containing just the new element.

You've provided 'get' procedures, why not start by providing a 'set' procedure? Doing so works towards completing your 'tree/node abstraction' and gives you a base set of functions to try to use in your 'insert' procedure.
(define (setLeftsubTree BST left)
(set-car! (cdr BST) left))
(define (setRightsubTree BST right)
(set-car! (cddr BST) right))
Now, in your insert code, when you want to 'go left' but there is no left, call setLeftsubTree with a newly created leaf node.

Related

Scheme Binary Search Tree Adding Elements

To begin, I wanted to write a function that:
Takes in:
A list of natural numbers, (list 2 6 1 23...) that could have repeating elements called "lst"
A random binary search tree called "bst"
Outputs:
An updated binary tree that adds every number on the list to it
Code
(define (recurse-lst bst lst)
(cond [(empty? roster) empty]
[(empty? lst) empty]
[else (recurse-lst (bst-add bst (first lst)) (rest lst))]))
; helper function
(define (bst-add bst sublst)
(cond [(empty? bst) (make-node (first sublst) empty empty)]
[(< (first sublst) (node-key bst))
(make-node (node-key bst)
(bst-add (node-left bst) (first sublst))
(node-right bst))]
[else
(make-node (node-key bst) (node-left bst)
(bst-add (node-right bst) (first sublst)))]))
Problem
I'm currently trying to get this working for nested lists; for example (list (list 1) (list 2)...), with each sub-list only having one element in them. However, it seems that it does not work and (first sublst) in bst-add turns the sublst into a number, like (first 1).
I think I've had similar bugs in other pieces of code before, but I cannot recall when and what it was.
right now you have
(define (recurse-lst bst lst)
(cond [(empty? roster)
....
"lst".
"roster".
you need always to include your error messages in the posts on SO.
next. you call (bst-add bst (first lst)) so the second argument in that call is already a number. yet in the definition of bst-add you name second parameter as "sublst" and treat it as a list. no need to take first again. and in fact taking first of a number is an error.

Implementing powerset in scheme

I am trying to implement a powerset function in Scheme in two ways.
One way is using tail recursion, and I did it like this:
(define (powerset list)
(if (null? list) '(()) ;; if list is empty, its powerset is a list containing the empty list
(let ((rest (powerset (cdr list)))) ;; define "rest" as the result of the recursion over the rest of list
(append (map (lambda (x) (cons (car list) x)) rest) ;; add the first element of list to the every element of rest (which is a sublist of rest)
rest)))) ;; and append it to rest itself (as we can either use the current element (car list), or not
Which works fine.
Another way is using foldr, and this is where I face some issues.
My current implementation is as follows:
(define (powerset-fr list)
(foldr (lambda (element result) ;; This procedure gets an element (and a result);
(if (null? result) ;; if starting with the empty list, there is nothing to "fold over".
(cons '() (cons element result))
(foldr (lambda (inner-element inner-result)
(append (cons element result) inner-result))
'(())
result)))
'() ;; The result is initialized to the empty list,
list)) ;; and the procedure is being applied for every element in the first list (list1)
Which yields a poor result.
I'll try to explain shortly how did I approach this problem so far:
foldr runs over every element in the given set. For each such element, I should add some new elements to the powerset.
Which elements should these be? One new element for each existing element in the powerset, where is append the current element in list to the existing element in powerset.
This is why I thought I should use foldr twice in a nested way - one to go over all items in given list, and for each item I use foldr to go over all items in "result" (current powerset).
I faced the problem of the empty list (nothing is being added to the powerset), and thus added the "if" section (and not just foldr), but it doesn't work very well either.
I think that's it. I feel close but it is still very challenging, so every help will be welcomed.
Thanks!
The solution is simpler, there's no need to use a double foldr, try this:
(define (powerset-fr lst)
(foldr (lambda (e acc)
(append (map (lambda (x) (cons e x))
acc)
acc))
'(())
lst))
If your interpreter defines append-map or something equivalent, then the solution is a bit shorter - the results will be in a different order, but it doesn't matter:
(define (powerset-fr lst)
(foldr (lambda (e acc)
(append-map (lambda (x) (list x (cons e x)))
acc))
'(())
lst))
Either way, it works as expected:
(powerset-fr '(1 2 3))
=> '((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) ())

how do you sum tree in scheme

;; A [BT X] is one of
;; - 'leaf
;; - (make-node X [BT X] [BT X])
(define-struct node (val left right))
;; interpretation: represents a node with a value
;; a left and right subtree
(define (tree-sum tree)
(cond
[(symbol=? tree 'leaf) ...] ;; the value remains same
[(node? tree)
(+ (tree-sum (node-val tree))
(tree-sum (node-left tree))
(tree-sum (node-right tree)))]))
not quite sure if i'm on the right track.
Normally, A pair tree is either
a leaf (not a pair), or
a pair, whose car and cdr values are pair-trees.
recursive summing procedure will have to deal with these two cases:
a numbers, i.e., leaves of a tree of numbers, and
pairs, in which case it should sum the left and right subtrees, and add those sums together.
Therefore,
(define (pair-tree-sum pair-tree)
(cond
[(number? pair-tree)
pair-tree]
[else
(+ (pair-tree-sum (car pair-tree))
(pair-tree-sum (cdr pair-tree)))]))
You can split the function into two parts - one that converts the tree into a list of numbers, and another that just uses foldl with that list, and foldl has the advantage of automatically doing the summation as an accumulator.
(define (tree->list tree)
(if (pair? tree)
(append (tree->list (car tree))
(tree->list (cdr tree)))
(list tree)))
(define (tree-sum tree)
(foldl + 0 (tree->list tree)))
You first need to check if the tree is empty, then if its not a list, else you call the function sum to the car of the list, and add to the cdr of the list.
(define (sum tree)
(cond [(empty? tree) 0]
[(not (list? tree)) (if (number? tree) tree 0)]
[else (+ (sum (first tree)) (sum (rest tree)))]))

Remove element off list

Someone tell me what is wrong with this code. I thought I mastered a few scheme skills to solve a friend's problem but it ended up messing my head. I am trying to remove all similar elements off the list. Earlier it was removing only the first element I want to remove, but now its removing the car and the first element f what I want to remove. I am looking for an output like: (delete 3 (list 2 3 4 3 5 3)), returns (2 4 5).
(define (delete n lst)
(cond
((null? lst) null)
((equal? n (car lst)) (cdr lst))
(else
(remove n (cdr lst)))))
It's because of this conditional:
((equal? n (car lst)) (cdr lst))
What this line does is it checks that n is the same as the first element in the list. If it is, it returns the rest of the list. Since your target element is the second element of the list, it returns the rest of the list, from the third element onward. Your first element in the list is completely dropped. You're not keeping track of the OK elements you've checked so far.
From your code, it looks like you want to loop through the elements of the list and, if you find your target value, call remove. If you want to implement it in this fashion, you need to also track the values that you've checked and verified that are not your target value. So your function needs to take three parameters: n, your target; lst the remaining numbers to check; and clean (or whatever you want to call it) that holds the already checked numbers.
This is a working version of your algorithm:
(define (delete n lst clean)
(cond
((empty? lst) clean)
((equal? n (car lst)) (delete n (cdr lst) clean))
(else
(delete n (cdr lst) (append clean (list (car lst)))))))
You'd call it like so: (delete 3 (list 2 3 4 3 5 3) '())
First it checks if you have numbers left to check. If you don't, it returns your clean list.
Then it checks to see if the first element matches your target element. If it does, then it calls delete again, effectively dropping the first element in the lst (notice it does not append it to the list of clean numbers).
The else, which is reached if the first element is not the target number, appends the first value of lst to the end of clean and calls delete again.
(Note that this code uses tail recursion, which is a way of writing recursive methods that track the intermediate values with each recursive call, as opposed to "regular" recursion that does the calculation at the end. Samrat's answer, below, is a regular recursive solution. A discussion of the tail recursion can be found here.)
From your post, it sounds like you want to remove all instances of the target number. Instead of using the remove function -- which only removes the first instance of the target number -- you should look at using the remove* function, which removes all instances. This would greatly simplify your function. So to remove all instances of 3 from your list, this would suffice:
(remove* '(3) (list 2 3 4 3 5 3))
If you wanted to wrap it in a function:
(define (delete n lst)
(remove* (list n) lst))
You should read up on map functions in general, since they pretty much do what you're looking for. (They apply a procedure against all elements in a list; The above could also be implemented with a filter-map if you had a more complicated procedure.)
Here's what I came up with:
(define (delete n lst)
(cond ((empty? lst) lst)
((= (car lst) n) (delete n (cdr lst)))
(else (append (list (car lst)) (delete n (cdr lst))))))

How can I get all possible permutations of a list with Common Lisp?

I'm trying to write a Common Lisp function that will give me all possible permutations of a list, using each element only once. For example, the list '(1 2 3) will give the output ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)).
I already wrote something that kind of works, but it's clunky, it doesn't always work and I don't even really understand it. I'm not asking for code, just maybe for some guidance on how to think about it. I don't know much about writing algorithms.
Thanks,
Jason
As a basic approach, "all permutations" follow this recursive pattern:
all permutations of a list L is:
for each element E in L:
that element prepended to all permutations of [ L with E removed ]
If we take as given that you have no duplicate elements in your list, the following should do:
(defun all-permutations (list)
(cond ((null list) nil)
((null (cdr list)) (list list))
(t (loop for element in list
append (mapcar (lambda (l) (cons element l))
(all-permutations (remove element list)))))))
Here is the answer which allows repeated elements. The code is even more "lispish" as it doesn't use loop, with the disadvantage of being less comprehensible than Rainer Joswig's solution:
(defun all-permutations (lst &optional (remain lst))
(cond ((null remain) nil)
((null (rest lst)) (list lst))
(t (append
(mapcar (lambda (l) (cons (first lst) l))
(all-permutations (rest lst)))
(all-permutations (append (rest lst) (list (first lst))) (rest remain))))))
The optional remain argument is used for cdring down the list, rotating the list elements before entering the recursion.
Walk through your list, selecting each element in turn. That element will be the first element of your current permutation.
Cons that element to all permutations of the remaining elements.

Resources