Does anybody know, how to get a list of leaf nodes in Prolog?
Let’s say, I have a simple directed graph described by these directed edges:
de(0,1).
de(0,2).
de(2,3).
de(2,4).
de(3,4).
de(4,5).
Now, how to recursively browse the graph and write a list of those 2 leaf nodes (node 1 & 5)?
Thanks for any answer!
Edit:
Well, I have 1st predicate written & working:
isLeaf(Node) :-
not(de(Node,_)).
but now, i have no idea how to traverse the graph and write the output list of leaf nodes. I know, it’s quite easy but I have no experience in this way of thinking and programming:(
You need to define a predicate
is_leaf/1that is a generator,i.e. it instantiates the input variable with possible solutions.
Something like this:
Usage examples:
Your solution immediately calls
not. (Btw, SWI-Prolog recommends using\+instead ofnot.)This means that your
isLeaf/2is not a generator: it either fails or succeeds (once), and never binds the input argument if it happens to be a variable.Also, it never tests that the input is a leaf, it just tests if it’s not a parent node.