%FILE: lp.p %TYPE: Prolog Source %Line: some generally useful list processing predicates %Date: 10/17/2017 writelist([]). writelist([H|T]) :- write(H), nl, writelist(T). member(X,[X|_]). member(X,[_|Y]) :- member(X,Y). length([],0). length([_|T],L) :- length(T,K),L is (1 + K). item(N,[H|_],H) :- N = 0. item(N,[_|T],E) :- N > 0, K is N - 1, item(K,T,E). append([],L,L). append([H|T1],L2,[H|T3]) :- append(T1,L2,T3). append(L1,L2,L3,Result) :- append(L1,L2,L12),append(L12,L3,Result). append(L1,L2,L3,L4,Result) :- append(L1,L2,L3,L123),append(L123,L4,Result). last([H|[]],H). last([_|T],Result) :- last(T,Result). remove(_,[],[]). remove(First,[First|Rest],Rest). remove(Element,[First|Rest],[First|RestLessElement]) :- remove(Element,Rest,RestLessElement). %remove(X, [X|Rest], Rest). %remove(X, [First|Rest], Z) :- % X \= First, Rest \= [], % remove(X, Rest, RestRemoved), % Z = [First|RestRemoved]. replace(0,Object,[_|T],[Object|T]). replace(ListPosition,Object,[H|T1],[H|T2]) :- K is ListPosition - 1, replace(K,Object,T1,T2). makelist(0,_,[]). makelist(Length,Element,[Element|Rest]) :- K is Length - 1, makelist(K,Element,Rest). reverse([],[]). reverse([H|T],R) :- reverse(T,Rev),lastput(H,Rev,R). lastput(E,[],[E]). lastput(E,[H|T],[H|L]) :- lastput(E,T,L). pick(L,Item) :- length(L,Length), random(0,Length,RN), item(RN,L,Item). take(List,Element,Rest) :- pick(List,Element), remove(Element,List,Rest). iota(0,[]). iota(N,IotaN) :- K is N - 1, iota(K,IotaK), lastput(N,IotaK,IotaN). sum([],0). sum([Head|Tail],Sum) :- sum(Tail,SumOfTail), Sum is Head + SumOfTail. min([H|[]],H). min([H|T],Min) :- min(T,CurrentMin), H < CurrentMin, Min = H. min([H|T],Min) :- min(T,CurrentMin), CurrentMin =< H, Min = CurrentMin. max([H|[]],H). max([H|T],Max) :- max(T,CurrentMax), H < CurrentMax, Max = CurrentMax. max([H|T],Max) :- max(T,CurrentMax), CurrentMax =< H, Max = H. sort_inc([H|[]],[H]). sort_inc(UnOrderedList,[H|OrderedTail]) :- min(UnOrderedList,H), remove(H,UnOrderedList,T), sort_inc(T,OrderedTail). sort_dec([H|[]],[H]). sort_dec(UnOrderedList,[H|OrderedTail]) :- max(UnOrderedList,H), remove(H,UnOrderedList,T), sort_dec(T,OrderedTail). alist([],[],[]). alist([H1|T1],[H2|T2],Alist):- length([H1|T1],L1), length([H2|T2],L2), L1 = L2, HeadPair = pair(H1,H2), alist(T1,T2,TailPairs), Alist = [HeadPair|TailPairs]. assoc([pair(K,V)|_],K,V). assoc([_|T],K,V) :- assoc(T,K,V). flatten([],[]). flatten([[]|T],L) :- flatten(T,L). flatten([H|T],L) :- atom(H), flatten(T,Tflattened), append([H],Tflattened,L). flatten([H|T],L) :- flatten(H,FlatHead), flatten(T,FlatTail), append(FlatHead,FlatTail,L).