Search code examples
prologb-treevisual-prolog

Prolog - Checking if a binary tree is ordered or not


I want to write a program in Prolog that confirms if a b-tree of integers is ordered or not. The order goes from smaller to greater. This is what I've written so far but I do not reach any solid work. Does someone know how to do that?

Domains
element=integer
tree=a(tree,element,tree);void

Predicates
     nondeterm ordre(tree)

Clauses
    order(a(_,Node,a(_,Node2,_))):-Node<Node2.
    order(a(Esq,Node,Dre)) :- 
        order(Esq), 
        write(Node),nl, 
        order(Dre).

Goal
       order(a(a(void,1,void),2,a(a(void,3,void),4,a(void,6,void)))).

Huge Thanks.


Solution

  • domains
        element = integer
        arbre = a (arbre, element, arbre) ; buit
    
    predicates
        nondeterm ordenat (arbre)
        nondeterm ordenat2 (arbre, element)
    
    clauses
        ordenat2 (a (buit, E, buit), E).
        ordenat2 (a (buit, E, R), MR) :-
            ordenat2 (R, MR),
            E<MR.
        ordenat2 (a (L, E, buit), E) :-
            ordenat2 (L, ML),
            ML<E.
        ordenat2 (a (L, E, R), MR) :-
            ordenat2 (L, ML), ML<E,
            ordenat2 (R, MR), E<MR.
    
        ordenat (A) :-
            ordenat2 (A, _).
    
    goal
        B=a (a (a (buit, 1, buit), 2, a (buit, 3, buit)), 4, a (a (buit, 5, buit), 6, a (buit, 7, buit))),
        ordenat (B)
        .
    

    Result: yes