Examples taken up in class


January 23, 2003

  • Effect of ordering of subgoals in the definition of a predicate.

    Consider the following TWO definitions of the predicate mult(X Y, Z), which evaluates to true if and only if X * Y = Z.

    
    Definition 1 :-
    
    mult(0, X, 0).
    mult(s(X), Y, Z) :- mult(X, Y, Z1), add(Y, Z1, Z). 
    
    add(0,X,X).
    add(s(X),Y,s(Z)) :- add(X,Y,Z).
    
    ----
    
    
    | ?- mult(X, Y, s(s(0))).
     
    X = s(0)
    Y = s(s(0)) ? ;
     
    X = s(s(0))
    Y = s(0) ? ;
     
    Fatal Error: global stack overflow (size: 8193 Kb, environment variable used: GLOBALSZ)
    
    	///////
    
    Definition 2 :-
    
    mult(0, X, 0).
    mult(s(X), Y, Z) :- add(Y, Z1, Z), mult(X, Y, Z1).
    
    add(0,X,X).
    add(s(X),Y,s(Z)) :- add(X,Y,Z).	
    
    ----
    
    | ?- mult(X, Y, s(s(0))).
     
    Fatal Error: global stack overflow (size: 8193 Kb, environment variable used: GLOBALSZ)
    
    
  • Permutation Definition:- /* erase(X, Y, Z) means Z is Y with one occurrence of X removed */ erase(X, [X|Y], Y). erase(X, [Y|Z], [Y|Z1]) :- erase(X, Z, Z1). /* perm(L1, L2) means L2 is a permutation of L1 */ perm([], []). perm([A|R], X) :- perm(R, X1), erase(A, X, X1). ---- Note the effect of changing the order of arguments to the predicate. | ?- perm([a,b,c], Ans). Ans = [a,b,c] ? ; Ans = [b,a,c] ? ; Ans = [b,c,a] ? ; Ans = [a,c,b] ? ; Ans = [c,a,b] ? ; Ans = [c,b,a] ? ; no | ?- program halts. | ?- perm(Ans, [a,b,c]). Ans = [a,b,c] ? ; Ans = [b,a,c] ? ; Ans = [c,a,b] ? ; Ans = [a,c,b] ? ; Ans = [b,c,a] ? ; Ans = [c,b,a] ? ; program does not halt!..
  • Simple counter using built-in functions

    Definition:- ctr(0). ctr(X) :- ctr(Y), X is Y + 1. ---- | ?- ctr(X). X = 0 ? ; X = 1 ? ; X = 2 ? ; X = 3 ? ; X = 4 ? goes on forever....
  • Insertion Sort

    Definition:- /* To sort a list, sort its tail, then insert its head in the right position. */ isort([Head|Tail],Result) :- isort(Tail,SortedTail), insert(Head,SortedTail,Result). isort([],[]). /* To insert an item into the correct position in a sorted list: Put it at the beginning if it should precede the first element; otherwise go down the list until a position is found where this is the case. */ insert(X,[Y|Tail],[X,Y|Tail]) :- X =< Y. insert(X,[Y|Tail],[Y|Z]) :- X > Y, insert(X,Tail,Z). insert(X,[],[X]). ---- Note the effect of changing the order of arguments to the predicate. | ?- isort([1,3,2], Ans). Ans = [1,2,3] ? ; no | ?- isort([1,3,2,0],Ans). Ans = [0,1,2,3] ? ; no | ?- isort([1,3,2,0,1],Ans). Ans = [0,1,1,2,3] ? ; no | ?- isort(Ans, [1,3,2]). Fatal Error: local stack overflow (size: 4096 Kb, environment variable used: LOCALSZ)