Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active June 7, 2022 02:17
Show Gist options
  • Save CMCDragonkai/9196cde3940ca4acb377311b03a9a604 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/9196cde3940ca4acb377311b03a9a604 to your computer and use it in GitHub Desktop.
Prolog: Even and Odd
%% 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)
@StefanSlev
Copy link

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).

@mwaseronnie
Copy link

Thanks @slevy97

@FearH4x
Copy link

FearH4x commented Nov 22, 2021

thanks <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment