Skip to content

Instantly share code, notes, and snippets.

@japaz
Created October 14, 2011 22:07
Show Gist options
  • Save japaz/1288497 to your computer and use it in GitHub Desktop.
Save japaz/1288497 to your computer and use it in GitHub Desktop.
7L7W Prolog - Day 2
% Some implementations of a Fibonacci series and factorials. How
% do they work?
% La sintaxis es factorial(N, F) -> Factorial de N es F (el resultado se guarda en F)
factorial(0, 1).
factorial(N, F) :- N>0, N1 is N - 1, factorial(N1, F1), F is N*F1.
%el factorial se llama recursivamente dejando el resultado en F
% Some implementations of a Fibonacci series and factorials. How
% do they work?
fibonacci(0,1).
fibonacci(1,1).
fibonacci(N,F) :- N > 1, N1 is N-1, N2 is N-2,
fibonacci(N1,F1), fibonacci(N2,F2), F is F1+F2.
% Imprime el resultado y sale del programa.
imprimir(N) :-write('El numero '),write(N),
write(' de la serie de Fibonacci es: '), fibonacci(N,X),
write(X), nl, fail.
% A real-world community using Prolog. What problems are they
% solving with it today?
% http://www.visual-prolog.com/vip/example/default.htm
% Speech Recognition
% Parser Generator
move(1,X,Y,_) :-
write('Move top disk from '),
write(X),
write(' to '),
write(Y),
nl.
move(N,X,Y,Z) :-
N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).
% Reverse the elements of a list.
reverse([X|Y],Z,W) :- reverse(Y,[X|Z],W).
reverse([],X,X).
append([], R, R).
append([H|T], R, [H|X]):-
append(T, R, X).
reverse2([X], [X]).
reverse2([H|T], R):-
reverse2(T, X), append(X, [H], R).
% Find the smallest element of a list.
append([], R, R).
append([H|T], R, [H|X]):-
append(T, R, X).
smallest([], []).
smallest([X], X).
smallest([X,Y], X) :- X<Y.
smallest([X,Y], Y) :- Y<X.
smallest([Head|Tail], S) :- smallest(Tail, R), append([Head],[R],T), smallest(T,S).
sortlist([],Solution) :- Solution = [].
sortlist([X], Solution) :- Solution = [X].
sortlist([X,Y], Solution) :- X=<Y, Solution = [X,Y].
sortlist([X,Y], Solution) :- X>Y, Solution = [Y,X].
sortlist([Head|Tail], Solution) :- higher(Head, Tail, Higher),
lower(Head, Tail, Lower),
sortlist(Higher, HigherS),
sortlist(Lower, LowerS),
append(LowerS, [Head], Solution1),
append(Solution1, HigherS, Solution).
higher(V, [L], Solution) :- L >= V,
Solution = [L].
higher(V, [L], Solution) :- L < V,
Solution = [].
higher(V, [Head|Tail], Solution) :- Head >= V,
higher(V, Tail, SolutionTail),
append([Head], SolutionTail, Solution).
higher(V, [Head|Tail], Solution) :- Head < V,
higher(V, Tail, SolutionTail),
append([], SolutionTail, Solution).
lower(V, [L], Solution) :- L < V,
Solution = [L].
lower(V, [L], Solution) :- L >= V,
Solution = [].
lower(V, [Head|Tail], Solution) :- Head < V,
lower(V, Tail, SolutionTail),
append([Head], SolutionTail, Solution).
lower(V, [Head|Tail], Solution) :- Head >= V,
lower(V, Tail, SolutionTail),
append([], SolutionTail, Solution).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment