I’m pretty new to Scheme and I’m having trouble writing a function as part of a homework. I have a graph G given to me as a list in the following format: ((node1 node2 weight1) (node3 node4 weight2) …). I’m trying to write a function that returns me the list of all nodes (V) in this graph in this format: (node1 node2 node3 …). The function may only take the graph (G) as input.
So I thought I can do this recursively by adding the first and second elements of each nested list within G, to V. Here’s what I have written:
(define nodes-of
(lambda (G)
(if (null? G)
()
(begin (add-to-set (cadar G) (nodes-of (cdr G)))
(add-to-set (caar G) (nodes-of (cdr G))))))
I think this is wrong though, as the first recursion only involves (cadar G) and the second involves (caar G), and the return value will be set only by the second statement under begin (if I’m not mistaken).
add-to-set is a function that I’ve written earlier for the homework, it adds an element to a list if it doesn’t already exist in the list. (eg: add-to-set n S , this will add n to S)
Can anybody help me with this? (btw I’m not allowed to use multiple let’s, let* or set)
Well, you are right that you can do it recursively, and your code is pretty close. Recall that every recursive procedure requires a base state for which you know the answer, and a way to reduce the complexity of the problem each time you recurse.
In the case of processing a list your base case is the empty list, which is why you want to check for null. Then the reduction formula will be breaking off a piece of the list then calling the procedure on the remaining part. So, like I said, you are close.
Realize then, that since your data is regularly structured you can just treat your graph as a normal list. You don’t need to recurse into every element of the list, you just want to perform two actions on every element and put the results in a list.
You could also use a
letif you wish..In your case you will use
add-to-setwhere I’ve usedcons. Once we’ve reached the base case, all of the calls toadd-to-setwill be able to be evaluated starting with the last one then working back down the stack to the first.