Reputation: 57
I am trying to learn Prolog and i have a really big problem to convert my programming knowledge to this language. I cant solve really newbie problems.
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 is an even number using this if i am not wrong
a(b(X)) mod 2 =:= 0
but i cant understand how to check it and print all numbers.
Upvotes: 3
Views: 2159
Reputation: 158
is_even(N) :- 0 =:= N mod 2. all_even_number :- a(b(X)), is_even(X), writeln(X), fail. all_even_number.
Upvotes: 0
Reputation: 5858
A very basic concept in prolog is pattern matching
there are plenty of tutorials explaining it, like this one
you might also want to check the first and rest of the second chapter.
one of the reasons i really like prolog is that i just write what i want:
I want to print all the X that have a certain attribute.
Lets describe the attribute first.
X has the attribute if it belongs to the database is even
has_attribute(X):-
belongs_db(X),
is_even(X).
X belongs in the database if there is a clause a(b(X))
belongs_in_db(X):-
a(b(X)).
X is even if the remainder of the division with 2 is 0:
is_even(X):-
0 =:= X mod 2.
now we can ask has_attribute(X) and prolog will reply, listing every X. but we want all X. to do this we will use the findall/3 predicate Find all X that have the attribute i want and put them in a list
findall(X,has_attribute(X),List).
now we have all the X in the list and we want to print them a simple way is to just use the writeln/1:
writeln(List)
so, in the end:
run:-
findall(X,has_attribute(X),List),
writeln(List).
has_attribute(X):-
a(b(X),
0 =:= X mod 2.
on the other hand, you may want to print the numbers in some other way. for this, you should use recursion
if the list is empty, i'm done
my_print_list([]).
if the list has a haed and tail i'll print the first element and then the tail:
my_print_list([Head|Tail]):-
writeln(Head),
my_print_list(Tail).
Upvotes: 7