Thursday, April 26, 2012

Seven Languages in Seven Weeks - Prolog Day 2 Self-Study

More fun with prolog! This self-study section consists in implementing some list operations.

Reverse the elements of a list
rev([], []).
rev([Head|Tail], List) :- append(X, [Head], List), rev(Tail, X).

Find the smallest element of a list.
min([X], X).
min([Head1|[Head2|Tail]], X) :- Head1 =< Head2, min([Head1|Tail], X).
min([Head1|[Head2|Tail]], X) :- Head1 > Head2, min([Head2|Tail], X).

Sort the elements of a list.
insert(X, [], [X]).
insert(X, [H|T], [X,H|T]) :- X =< H.
insert(X, [H|T], [H|Rest]) :- X > H, insert(X, T, Rest).

isort([], Acc, Acc).
isort([H|T], Acc, Sorted) :- insert(H, Acc, Acc2), isort(T, Acc2, Sorted).

No comments:

Post a Comment