Skip to content

Instantly share code, notes, and snippets.

@hackerghost93
Created April 1, 2016 12:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hackerghost93/52abf27f143bf378639011c76f84070f to your computer and use it in GitHub Desktop.
Save hackerghost93/52abf27f143bf378639011c76f84070f to your computer and use it in GitHub Desktop.
Some list operation implemented in Prolog.
/*This to call the outside function .. the inside function "average"
calculate the result and give it back to the outside function
"avg"
*/
avg(List,Ans):-
Count is 0,
Sum is 0 ,
average(List,Count,Sum,Ans).
/* This is the most important line you need to handle base case well use trace command in SWI-PROLOG
to see what is happening in your calls */
average([],Count,Sum,Ans):-
Ans is Sum/Count .
average([X|List],Count,Sum,Ans):-
C is Count+1,
S is Sum+X ,
average(List,C,S,Ans).
inter(List1,List2,In):-intersection(List1,List2,[],In).
intersection([],_,X,X).
intersection([H|List1],List2,X,In):-
member(H,List2),
intersection(List1,List2,[H|X],In).
intersection([H|List1],List2,X,In):-
not(member(H,List2)),
intersection(List1,List2,X,In).
maxi([H|List],Ans):-max(List,H,Ans).
max([],H,H).
max([H|List],X,Ans):-
H > X ,
max(List,H,Ans).
max([H|List],X,Ans):-
H < X,
max(List,X,Ans).
reverse([],X,X).
reverse(List,NList):-
reverse(List,[],NList).
reverse([X|List],NList,Reversed):-
reverse(List,[X|NList],Reversed).
union(X,Y,Ans):-
unique(X,List1),
unique(Y,List2),
unify(List1,List2,[],Ans).
unify([],List2,X,Ans):-
append(List2,X,Ans).
unify([H|List1],List2,X,Ans):-
member(H,List2),
unify(List1,List2,X,Ans).
unify([H|List1],List2,X,Ans):-
not(member(H,List2)),
unify(List1,List2,[H|X],Ans).
/* another solution easy one */
/* union(X,Y,Ans) :-
append(X,Y,L),
unique(L,Ans).
*/
unique(List1,U):- uni(List1,[],U).
/*base case the remove from stack in recursion will empty the temp list so i need to save the output in something else .. here in this code is RET ->
the line says that Temp = Ret and empty list will be a true statement*/
uni([],X,X).
uni([H|Tail],Temp,Ret):-
member(H,Tail),
uni(Tail,Temp,Ret).
/*the procedure goes like this if the head of this list , is not in the tail
therefor this is a non duplicate element , add it with , */
uni([H|Tail],Temp,Ret):-
not(member(H,Tail)),
uni(Tail,[H|Temp],Ret).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment