Comp Sci 538 Lecture Notes for April 21 Merge Sort in Prolog Merge([], L, L). Merge(L, [], L). Merge([A | T1], [B | T2], [A | L2]) :- A =< B, Merge(T1, [B | T2] , L2). Merge([A | T1], [B | T2], [B | L2]) :- A > B, Merge([A | T1, T2, L2). Split([], [], []). Split([A], [A], []). Split([A, B | T], [A | P1], [B | P2]) :- Split(T, P1, P2). MergeSort([], []). MergeSort([A], [A]). MergeSort(L1, L2) :- Split(L1, P1, P2), MergeSort(P1, S1), MergeSort(P2, S2), Merge(S1, S2, L2). Keeps dividing the list until there are lists of size 1 or 0 (depends if you start with an even or odd number of elements). Takes log2 n to divide Total time is n log2 n Arithmetic in Prolog 2 = 1 +1 returns no because 2 (an integer) is not the same as 1+1 (a function) ?- 1 = 2. comparison no ?- x = 2. assignment x = 2 ?- x = y. assigning unknowns to the same unknown x = _1 y = _1 _1 is an internal variable ?- x = y, y = joe. x = _1 y = _1 does left side first y = _1 = joe x = _1 = joe x = y is same as y = x, Prolog is symmetric from above 1 + 1 is a standard form of +(1, 1) which is more evident that 2 = +(1, 1). returns no is form of = used only in arithmetic expression, both assignment and comparison 2 is 1 + 1. yes x is 1 * 2. x = 2 y is x + 1 no good if x is unbound (0 is (I**N) + (J**N) - (K**N)), N > 2. unfortunately won't work, very difficult to implement len(L, N) L will be a list N will be its length len([], 0). len([H | T], N) :- len(T, M), N is M+1. Prolog can count the number of terms and functions with different number of terms are unique. adj([A, B | T]) :- A = B. adj([_, B | T]) :- adk([B | T]). adj is mistyped adk will always return no to adk([B | T]) since no rules exist for it, run-time error member(A, [A | _]). member(A, [_ | T]) :- member(A, [T]). T is already a list, now it is a nested list member(2, [1, 2]). infinite loop A = 2 T = [2] member(2, [[2]]). [[2]] is equivalent to [[2] | []] A = 2 T = [] member(2, [[]]). odd(1). odd(n) :- odd(M), N is M+2. odd(x), x = 2. infinite search pattern generates M = 1 does 1 = 2 no M = 3 does 3 = 2 no M = 5 does 5 = 2 no ...