/* Example 1: 2D array implemention. B. Ross, Brock University, 2002 The table is a list of entries. Each entry has the form (Row, Col, Data), where Row and Col are indices into the table position. */ test :- table(T), set_row(2, [2,3,4], T, T2), set_col(3, [a,b,c], T2, T3), set_item(T3, 2, 2, cat, T4), print_table(T4). table([(1,1,0), (1,2,0), (1,3,0), (2,1,0), (2,2,0), (2,3,0), (3,1,0), (3,2,0), (3,3,0)]). % set_row(RowNum, Vals, Table, NewTable) takes the array of Vals (fits exactly % in a table row) and replaces row #RowNum in Table with it. set_row(RowNum, RowVals, Table, NewTable) :- length(RowVals, Max), set_row2(1, Max, RowNum, RowVals, Table, NewTable). set_row2(N, Max, _, _, NewTable, NewTable) :- N > Max. set_row2(N, Max, RowNum, [Val|Rest], Table, NewTable) :- N =< Max, set_item(Table, RowNum, N, Val, Table2), M is N+1, set_row2(M, Max, RowNum, Rest, Table2, NewTable). % like set_row, but replaces a column... set_col(ColNum, ColVals, Table, NewTable) :- length(ColVals, Max), set_col2(1, Max, ColNum, ColVals, Table, NewTable). set_col2(N, Max, _, _, NewTable, NewTable) :- N > Max. set_col2(N, Max, ColNum, [Val|Rest], Table, NewTable) :- N =< Max, set_item(Table, N, ColNum, Val, Table2), M is N+1, set_col2(M, Max, ColNum, Rest, Table2, NewTable). % set_item(Table, R, C, Val, NewTable) replaces entry (R,C,_) with % (R,C,Val). NewTable is the result. set_item([(Row,Col,_)|Rest], Row, Col, Val, [(Row,Col,Val)|Rest]) :- !. set_item([Entry|Rest], Row, Col, Val, [Entry|Rest2]) :- set_item(Rest, Row, Col, Val, Rest2). % Read an entry from the table... read_value(Row, Col, Table, Val) :- member((Row, Col, Val), Table), !. % Print the table to standard output. The table entries can be in any order % whatsoever, as this predicate prints them out in the proper order. print_table(T) :- length(T, L), Max is integer(sqrt(L)), print_rows(1, Max, T). print_rows(N, Max, _) :- N > Max, !, nl. print_rows(N, Max, T) :- print_row(N, 1, Max, T), M is N+1, print_rows(M, Max, T). print_row(_, C, Max, _) :- C > Max, !, nl. print_row(R, C, Max, T) :- read_value(R, C, T, Val), write(Val), write(' '), C2 is C+1, print_row(R, C2, Max, T). member(A, [A|_]). member(A, [_|R]) :- member(A, R).