Created
March 26, 2024 11:22
-
-
Save aarmn/68323f252296cf4c9b86d20549ea3468 to your computer and use it in GitHub Desktop.
2 simple programs in prolog, to get started with prolog,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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