/* CLP(R) CSE 341 Homework 8 Solution */ /* append */ append([],L,L). append([H|T],L,[H|U]) :- append(T,L,U). /* sum */ sum([],0). sum([X|Xs],X+S) :- sum(Xs,S). /* abs */ abs(X,-X) :- X < 0. abs(X,X) :- X >= 0. /* listmax */ listmax ([A],A). listmax ([A|Xs],A) :- listmax(Xs,B), B <= A. listmax ([X|Xs],A) :- listmax(Xs,A), A > X. /* listindex(L,I,X) <==> list L has X at index I */ listindex ([X|Xs],0,X). listindex ([_|Xs],I,X) :- I > 0, listindex(Xs,I-1,X). /* matrixindex(M,I,J,X) <==> matrix M has X at (I,J) */ matrixindex (M,I,J,X) :- listindex(M,I,Row), listindex(Row,J,X). /* Row is the Ith row of M */ matrixrow(M,I,Row) :- listindex(M,I,Row). /* matrixcol(M,I,Col) <==> Col is the Ith column of M */ matrixcol([],I,[]). matrixcol([Row|Rest],I,[X|Xs]) :- listindex(Row,I,X), matrixcol(Rest,I,Xs). /* listall(L,X) <==> all elements of list L are identical to X */ listall([],X). listall([X|Xs],X) :- listall(Xs,X). /* length */ length([],0). length([_|Xs],1+L) :- L >= 0, length(Xs,L). /* rows/cols as defined in text */ rows([_,_]). rows([R1,R2,R3|Rs]) :- cols(R1,R2,R3), rows([R2,R3|Rs]). cols([_,_],[_,_],[_,_]). cols([TL, T, TR | Ts],[ML, M, MR | Ms],[BL, B, BR | Bs]) :- M = (T + ML + MR + B)/4, cols([T,TR|Ts],[M,MR|Ms],[B,BR|Bs]). /* * constructs a plate with N, S, E, W as * north, south, east, and west sides */ plate(P,N,S,E,W) :- length(P,9), listall(Nrow,N), length(Nrow,9), matrixrow(P,0,Nrow), listall(Srow,S), length(Srow,9), matrixrow(P,8,Srow), listall(Ecol,E),append([N|Ecol],[S],Eside), matrixcol(P,8,Eside), listall(Wcol,W),append([N|Wcol],[S],Wside), matrixcol(P,0,Wside). /* * this runs our experiment and returns N,S,E,W */ exper(N,S,E,W) :- plate(P,N,S,E,W), matrixindex(P,4,4,50), matrixindex(P,2,4,90), matrixindex(P,4,6,90), rows(P). /* * this runs our experiment and returns N,S,E,W */ exper2(N,S,E,W) :- P = [[_, N, N, N, N, N, N, N, _], [W, _, _, _, _, _, _, _, E], [W, _, _, _, 90, _, _, _, E], [W, _, _, _, _, _, _, _, E], [W, _, _, _, 50, _, 90, _, E], [W, _, _, _, _, _, _, _, E], [W, _, _, _, _, _, _, _, E], [W, _, _, _, _, _, _, _, E], [_, S, S, S, S, S, S, S, _]], rows(P).