Last active
June 7, 2022 02:17
-
-
Save CMCDragonkai/9196cde3940ca4acb377311b03a9a604 to your computer and use it in GitHub Desktop.
Prolog: Even and Odd
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
%% The `=` is Prolog unification operator, it does not perform arithmetic evaluation. | |
%% That means `8 = 4 + 4` is false in Prolog. | |
%% Instead you can use `8 is 4 + 4` or `8 =:= 4 + 4`. | |
%% The unification operator tries to unify intensional structure, and `8 = 4 + 4` is | |
%% trying to unify `'+'(4, 4)` with `8`. | |
%% However `8 = 8` unifies! | |
even(0). | |
even(X) :- X > 0, X1 is X - 1, odd(X1). | |
even(X) :- X < 0, X1 is X + 1, odd(X1). | |
odd(1). | |
odd(X) :- X > 0, X1 is X - 1, even(X1). | |
odd(X) :- X < 0, X1 is X + 1, even(X1) |
Thanks @slevy97
thanks <3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could do much faster by using the "mod" function like this:
even(X) :- 0 is mod(X, 2).
odd(X) :- 1 is mod(X, 2).