Counting occurrences in a list
count_word(_,[],0).
count_word(W,L,C) :-
L = [H|T],
count_word(W, T, X),
(W = H -> ToAdd=1; ToAdd=0),
C is ToAdd + X. % crucial line
Sum of list:
sumList([],0).
sumList(L,N) :-
L = [H|T],
sumList(T,X),
N = X + H.
Factorials:
fact(X, 1).
fact(X, N) :-
NewX is X - 1,
fact(NewX, NewProd),
N is NewProd * X.
Sorting:
bubblesort(L, Sorted) :-
append(X, [X1, X2|T], L),
X2 < X1, % Sorting condition here
append(X,[X2,X1|T], L), Sorting),
bubblesort(Sorting, Sorted),
!.
bubblesort(L, L).
Followed by:
followedBy(X,Y,L) :- append(_, [X,Y|_],L).
Last:
last(E,L) :- append(_, [E], L).
Setof removes all duplicate elements
Syntax is findall(Element,(Conditions), List)
Good for creating lists
studentsInHouseByID(House, SortedByID) :-
findall(SID, student(SID, _, House), UnsortedByID),
And filtering them
filterByCourseID(OldList, MustStudy, NewList) :-
findall(Name, (member(Name, OldList), student(SID, Name, _), enrolled(SID, MustStudy)), NewList).
length(L,N)
member(E,L)
reverse(L, ReversedList)
Negation is \+()
. If adding in compound statements, make sure to wrap those in brackets as well (because negation takes only one argument).
Less than <
, lte =<
, greater than >
, gte >=
, equal to (assignment) =
, evaluate, then assign is
.
If/Else is ( condition -> then_clause ; else_clause )
.
Cut operator is !
. Add to expose base case (see bubblesort above).