% CPSC 312 2019 - Midterm 3 vwersion A

:- use_module(library(clpfd)).  % defines #< for integers..

%Question 1

% "g is not a logical consequence of KB" means there is a model of KB in which g is false

% KB is
:- dynamic t/0.
w :- x, y.
x :- u, v.
u :- s.
s.
v :- y.
y :- t.

% (a) x :- u,v.
% (b) s.
% (c) yes :- y,y.

% There are no clauses for t

%  Question 2


:- dynamic m/0.
a :- b,c,d.
a :- e.
b :- g.
b :- m.
g.
c :- m.
e :- g.
d.

% Load this file then do
% ?- [trace].
% ?- a.

% Question 3

elem(E, set(E,_,_)).
elem(V, set(E,LT,_)) :-
    V #< E,
    elem(V,LT).
elem(V, set(E,_,RT)) :-
    E #< V,
    elem(V,RT).

%?- elem(X, set(7,set(2,empty,empty),set(9,empty,set(11,empty,empty)))).
% ?- elem(3,S),elem(8,S).
%  S = set(3, _1094, set(8, _1108, _1110))
% Note that Prolog doesn't know anything about empty, so the subtrees can't be empty. The subtrees are different variables.

% insert(E,S,S1) is true if S1 is a set containing E and the elements of set S
insert(V,empty,set(V,empty,empty)).
insert(V,set(V,L,R),set(V,L,R)).
insert(V,set(E,L,R),set(E,L1,R)) :-
    V #< E,
    insert(V,L,L1).
insert(V,set(E,L,R),set(E,L,R1)) :-
    E #< V,
    insert(V,R,R1).


%?- insert(3, set(7,set(2,empty,empty),set(9,empty,set(11,empty,empty))), R).

% Question 4

% myapply(Lst, Sub, Res) where sub is a list of (X,Y) pairs, replaces each element of X by Y

myapply([], _, []).
myapply([H|T], Sub, [H1|T1]) :-
    app(H, Sub, H1),
    myapply(T, Sub, T1).

app(E,[],E).
app(E,[(E,V)|_],V).
app(E,[(E1,_)|R],V) :-
    dif(E,E1),
    app(E,R,V).

%?- myapply([a,b,c,d,e,c], [(a,f), (c,3), (g,7)], R).
%?- myapply([b,a,a,b], [(a,b),(b,a)], R).
%?- myapply([b,a,a,b], S, [c,c,c,c]).

