Prolog and facts in the database

0

Good morning, I'm learning prolog and I have some questions for you. I want to know more about how these problems are made more than the final answer since my intention is to learn and not solve the exercise directly.

My question is

I have a binary tree defined as follows

arbol(Id, R, HI, HD)

For example, the next tree

It is defined as follows

arbol(a4,6,b3,b4).
arbol(b3,7,c1,c2).
arbol(c1,5,d1,nil).
arbol(d1,1,nil,nil).
arbol(c2,3,nil,d2).
arbol(d2,4,nil,nil).
arbol(b4,8,c3,c4).
arbol(c3,10,nil,nil).
arbol(c4,11,d3,d4).
arbol(d3,9,nil,nil).
arbol(d4,2,nil,nil).

These are facts in my facts database. So my first question is how can I identify the parent of an N node in this database. For example:

?-padre(3,a4,P).
P=7
?-padre(6,a4,P).
false

The parent predicate / 3 can be explained as:

father (N, Abn, P).

N = Nodo al cual se quiere averiguar su padre
Abn = Árbol donde se está haciendo la búsqueda. Si a4, en este caso sería el árbol completo
P = Padre del nodo N

I thought about making use of the findall/3 predicate but with e I would return a list when I want it to return a node.

I think I could use predicates such as retract or asserta to modify the database and reach the solution, but I'm not sure.

Thank you.

    
asked by Aceconhielo 09.06.2017 в 20:31
source

1 answer

0

You do not need a findall for your example, just looking for the node as a right child or a left child is enough. Then, look for the father and the id of the tree that has as root the parent node:

padre(Nodo, IdArbol, Padre):-
 arbol(Id, Nodo, _, _),
 arbol(IdArbol, Padre, Id,_).

padre(Nodo, IdArbol, Padre):-
 arbol(Id, Nodo, _, _),
 arbol(IdArbol, Padre, _, Id).
    
answered by 28.03.2018 в 23:02