Skip to content

Instantly share code, notes, and snippets.

@xdl
Last active January 3, 2016 04:49
Show Gist options
  • Save xdl/8411192 to your computer and use it in GitHub Desktop.
Save xdl/8411192 to your computer and use it in GitHub Desktop.

Prolog tips

Using recursion

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).

Using append

Followed by:

followedBy(X,Y,L) :- append(_, [X,Y|_],L).

Last:

last(E,L) :- append(_, [E], L).

Using member with setof/findall

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).

Other functions

  • length(L,N)
  • member(E,L)
  • reverse(L, ReversedList)

Syntax

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment