Educational prologue

I am trying to learn Prolog, and I have a really big problem to translate my programming knowledge into this language. I can’t really solve the problems with beginners.

For example, I have this

a(b(1)).
a(b(2)).
a(b(3)).
a(b(4)).
a(b(6)).

The exercise wants to print (using writeln (X)) all b (Y) if Y is an even number.

I can find if it's an even number using this, if I'm not mistaken

a(b(X)) mod 2 =:= 0

but I can’t figure out how to check it and print all the numbers.

+3
source share
2 answers

A very simple concept in the prologue - this pattern matching
there are many tutorials explaining this, for example this one you can also check the first and second chapters.

, , - , :

X, .
.

X if

has_attribute(X):-
    belongs_db(X),
    is_even(X).

X , a (b (X))

belongs_in_db(X):-
    a(b(X)).

X 2 0:

is_even(X):-
    0 =:= X mod 2.

has_attribute (X), , X. , X. , findall/3 X, , ,

findall(X,has_attribute(X),List).

X , , writeln/1:

writeln(List)

, :

run:-
    findall(X,has_attribute(X),List),
    writeln(List).

has_attribute(X):-
     a(b(X),
     0 =:= X mod 2.

, .

,

my_print_list([]).

, , :

my_print_list([Head|Tail]):-
    writeln(Head),
    my_print_list(Tail).
+7
is_even(N) :-
        0 =:= N mod 2.

all_even_number :-
       a(b(X)),
       is_even(X),
       writeln(X),
       fail.
all_even_number.
0

All Articles