Scheme Path In Binary Tree - scheme

I got an exercice to find the path of a binary tree in Scheme.
Basically, it's like Find all paths from root to leaves of tree in Scheme.
But instead of printing the value of nodes, we have to print the way to get to the leaf. ( print : right left left right for ex)

If you are talking about finding the path from root to a specific leaf you can basically search your tree recursively and while doing that you should pass a list to your search function as parameter to keep track of the path already taken and your search function should return path list.
For example, let's say you are searching for L in your tree, you need to check whether L is in left or right subtree. After finding the subtree in which L is located you can basically add the direction to your path list, you can do something like
(define (search L tree)
(cond
((null? tree) '() )
((member L leftsubtree ) (cons 'left (search L leftsubtree))
((member L rightsubtree) (cons 'right (search L rightsubtree)))))
What we do here is we found the subtree L is located and then add the direction (left or right) to the front of the path from parent of that subtree to L. Of course if you copy and paste this code it does not work. So you need to implement this function in accordance with your tree representation, and you probably need to implement member function for your case. I hope it helps.

(define (ab-chemin-aux AB e CH)
(if (ab-noeud? AB)
(if (equal? e (ab-etiquette AB))
CH
(or (ab-chemin-aux (ab-gauche AB) e (append CH (list "gauche")))
(ab-chemin-aux (ab-droit AB) e (append CH (list "droit")))))#f))
(define (ab-chemin AB e)
(ab-chemin-aux AB e (list)))
I figured out the answer but I forgot about asking here. Thank you for your answer. Hope this help someone

Related

Why does DrRacket seem to identify this as a tail call?

Consider this snippet:
#lang racket
(define (f i)
(if (> i 5)
0
(+ 1 (f (+ 1 i)))))
Here, the call to f is not in tail position, and when I debug, I see a growing stack of the form
(+ ...)
(f ...)
(f ...)
(f ...)
(f ...)
This is expected. However, when I hover over the beginning of the last line, a light purple arrow appears and points to the beginning of the function definition. If I understand the documentation correctly, it indicates tail position. What am I missing?
The form which is the last line is in tail position with respect to f. The recursive call to f, however, isn't: if you hover over the f you'll get a pale blue arrow which tells you that it's the same f the function is binding. Here's a screenshot showing both things:
All of the (if ...) form and both of its consequents are in tail position. The f is the same f defined by the function, but is not in tail position.
When you move to B and you see A ➯ B. It means you can find B's define in A.
When you move to A and you see A ➯ B. You can see variable bound occurrence.

Building trees starting from a list of symbols

I have a list of symbols which are organized by well formed parenthesis and I want to generate a tree like this one:
Leaf nodes are the symbols and the non-terminal nodes represent the parenthesis and I want to store in a strucuter both them.
Is there a way to build this tree?
It should be easy to split the whole formula into chunks that are direct descendants, while each chunk is well-formed. Use counting of nesting level for that: an opening parenthesis increases the level, a closing parenthesis decreases the level, and whenever the nesting level is 0, there is a boundary between chunks.
This way, you can convert
((a b) (c d)) e ((f g h) i)
into its constituent parts:
((a b) (c d))
e
((f g h) i)
For each part, if it contains more than one symbol, run the same algorithm recursively.
Certainly. First, if you implement a language in which parentheses are syntactic collecting punctuation (e.g. Python lists), you can likely use a built-in evaluation function to parse your input into a desirable structure.
Failing that ... I believe that the below is merely a more detailed version of the previous answer. The steps are simple (recursion should be simple, neh?):
If the input is atomic, make this a leaf node and return.
Split the given list into elements at every internal 0 in the open parenthesis count.
For each element in this list:
3a. Remove the outermost parentheses;
3b. Reduce the parenthesis counts by 1 each;
3c. Recur on this element.
Now, let's walk through the example you give.I'm ignoring the original root node text, in favor of the structure you show in the tree:
[(A ((B C) (D E)))(F G (H I L))]
At each level, the first thing to do is to strip off the outermost parentheses (actually brackets, in this case. I'm not sure why you have a different symbol on the outside).
(A ((B C) (D E)))(F G (H I L))
Now, start at the front, keeping count of how many open parentheses you have.
(A ((B C) (D E)))(F G (H I L))
1 23 2 3 2101 2 10
Note: If you need to throw syntax errors for an imbalance, you have a
nice check: the final count must be 0, with no following characters.
Wherever you have a 0 in the middle, break the string (marked with ^):
(A ((B C) (D E))) ^ (F G (H I L))
1 23 2 3 210 1 2 10
Now, recur on each element you found. If the element is atomic, it's a leaf node.
If you want to save counting time, carry the count as another argument to the routine. Reduce it by 1 on recursion.
^
A ((B C) (D E)) F G (H I L)
12 1 2 10 1 0
The left side has two elements: a leaf node A, and another expression on which we recur:
((B C) (D E))
12 1 2 10
There is no internal 0, so we trivially recur on the entire list:
(B C) (D E)
1 0 1 0
This break into two lists, (B C) and (D E)
Similarly, the right branch of the root node breaks into three elements: F, G, and (H I L). Handle these the same way.

Comparing two lists in scheme

I am trying to recursively compare and output the smallest number in 2 equal sized set of lists. Example (testFunc '(3 5 9) '(1 2 11)) will return '(1 2 9). I have tried the following:
(define (testFunc X Z)
(if (< (car X) (car Z)) ((car X) (testFunc((cdr X) (cdr Z))))
((car Z) (testFunc((cdr X) (cdr Z))))))
My thought process and what I am trying to achieve:
compare the first element of X and Z. If x(1) is smaller than z(1) then print x(1) and drop the first element from both lists using cdr and repeat the process by calling testFunc else print z(1) and do the same thing until we went through each position.
Appreciate all the help in advance. Thanks!
To call testFunc, you must use (testFunc arg1 arg2). You must not use (testFunc(arg1 arg2)). Scheme is parenthesis-sensitive; you must not add (or remove) extra parentheses.
Likewise, to bunch up the results, you need to use (cons item rest), and not just (item rest).
Have you considered using just (map min list1 list2)?
What you want is the k-minor numbers from 2 lists where k is the size of both lists. There are many ways to do this.
Here's one idea:
First append both lists.
Then sort them from lower to higher.
Then take the first three.
But that wouldn't be exactly recursive (sort is recursive but the procedure as such is not).
So another idea uses tail recursion using a list that saves the returning result and we'll name it res and a procedure that gets the minor item from a list called min-list.
Check if length of res is k. If so, return res.
Otherwise let minorA= (min-list A), minorB=(min-list B)
Finally:
if minorA < minor B
recursive call with A=(remove minorA A) B=B, res=(cons minorA res), k=k
else recursive vall with A=A B=(remove minorB B), res=(cons minorB res), k=k
And this idea is in fact recursive.
I got the code written but I want you to try and code it yourself so please tell us of any doubt.
Happy coding!
EDIT:
I've read the comments and it seems you can't use min. Does this mean you cannot use the one that comes in racket/base? If so, you can write your own procedure to check which is the minimal value but if you're not allowed even that, then we'll have to try something else. (I'll post here next idea when I get one).
Oh, and please, clarify the form of the input lists, are they ordered from minor to greater? In your example it seems that way but if it's not always like that then the procedure can change a bit.

emacs org-mode tree to list

I'm looking for a concise way to read a specific tree (including subtrees) into a list.
Say I've got:
* Branch
** Small branch
** Another small branch
*** Leaves
* Flowers
The function should be able to search by regular expression and copy the subtree (e.g. search for Branch) to a list like:
'(("Small branch") ("Another small branch" ("Leaves")))
The following seems to work:
(defun org-list-siblings ()
"List siblings in current buffer starting at point.
Note, you can always (goto-char (point-min)) to collect all siblings."
(interactive)
(let (ret)
(unless (org-at-heading-p)
(org-forward-heading-same-level nil t))
(while (progn
(setq ret (cons (append (list (substring-no-properties (org-get-heading)))
(save-excursion
(when (org-goto-first-child)
(org-list-siblings))))
ret))
(org-goto-sibling)))
(nreverse ret)))
If you do not need the full tree but a sub-tree put point on the first of its children headings.
That is methodical since the top-level headings are interpreted as the first children. There is no common root.

Finding keys closest to a given value for clojure sorted-maps

For clojure's sorted-map, how do I find the entry having the key closest to a given value?
e.g. Suppose I have
(def my-map (sorted-map
1 A
2 B
5 C))
I would like a function like
(find-closest my-map 4)
which would return (5,C), since that's the entry with the closest key. I could do a linear search, but since the map is sorted, there should be a way of finding this value in something like O(log n).
I can't find anything in the API which makes this possible. If, for instance, I could ask for the i'th entry in the map, I could cobble together a function like the one I want, but I can't find any such function.
Edit:
So apparently sorted-map is based on a PersistentTreeMap class implemented in java, which is a red and black tree. So this really seems like it should be doable, at least in principle.
subseq and rsubseq are very fast because they exploit the tree structure:
(def m (sorted-map 1 :a, 2 :b, 5 :c))
(defn abs [x] (if (neg? x) (- x) x))
(defn find-closest [sm k]
(if-let [a (key (first (rsubseq sm <= k)))]
(if (= a k)
a
(if-let [b (key (first (subseq sm >= k)))]
(if (< (abs (- k b)) (abs (- k a)))
b
a)))
(key (first (subseq sm >= k)))))
user=> (find-closest m 4)
5
user=> (find-closest m 3)
2
This does slightly more work than ideal, in the ideal scenario we would just do a <= search then look at the node to the right to check if there is anything closer in that direction. You can access the tree (.tree m) but the .left and .right methods aren't public so custom traversal is not currently possible.
Use the Clojure contrib library data.avl. It supports sorted-maps with a nearest function and other useful features.
https://github.com/clojure/data.avl
The first thing that comes to my mind is to pull the map's keys out into a vector and then to do a binary search in that. If there is no exact match to your key, the two pointers involved in a binary search will end up pointing to the two elements on either side of it, and you can then choose the closer one in a single (possibly tie breaking) operation.

Resources