Skip to content

Instantly share code, notes, and snippets.

@aarmn
Created March 26, 2024 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarmn/68323f252296cf4c9b86d20549ea3468 to your computer and use it in GitHub Desktop.
Save aarmn/68323f252296cf4c9b86d20549ea3468 to your computer and use it in GitHub Desktop.
2 simple programs in prolog, to get started with prolog,
% Factorial in Prolog, its as clear as it can be, no need for report.
% By AARMN The Limitless (Alireza Mohammadnezhad)
% Factorial base case
factorial(0, 1). % factorial of 0 is 1
% Factorial recursive logic
factorial(N, Return) :-
N > 0, % Not really needed, just stopping negetive values, a failsafe
NDec is N - 1, % Decrease value
factorial(NDec, ReturnDec), % Recursive call, put out of it in ReturnDec
Return is N * ReturnDec. % Recursive logic, put output in Return variable
% a helper predicate to take input for a function/1 (function with arity 1, aka unary)
prompt(X) :-
write('Please enter a value: '),
read(Value),
call(X, Value, Out),
write('\nAnswer is: '),
write(Out).
f :- prompt(factorial). % calling prompt for factorial for ease of call.
% Hanoi Tower in Prolog, its as clear ans it can be, no need for report.
% By AARMN The Limitless (Alireza Mohammadnezhad)
% Hanoi base case
hanoi(0, _, _, _) :- !. % Using cut operator to signify end of recursion
hanoi(N, S, T, A) :-
NDec is N - 1, % Decrease N by 1
hanoi(NDec, S, A, T), % 1st recursive call
format('Move disk from ~w to ~w~n', [S, T]), % the action, instead of direct returing we print result of recursion along the way
hanoi(NDec, A, T, S). % 2nd recursive call
% a helper predicate to take input for a function/1 (function with arity 1, aka unary)
prompt(X) :-
write('Please enter a value: '),
read(Value),
call(X, Value, source, target, auxilary).
f :- prompt(hanoi). % calling prompt for hanoi for ease of call.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment