Re: how to make this fail driven loop succesfull ?
"Richard A. O'Keefe" <[email protected]>
| Newsgroups | gmane.comp.ai.prolog.swi |
|---|---|
| Message-ID | <[email protected]> |
On 9/03/2014, at 10:43 AM, Bob Minors wrote:
>
> siblings(Father,Mother) :- is_father(X, Father), is_mother(X, Mother), write(X), nl, fail ; true.
By the way, the predicate name here is rather odd.
If I see siblings(X, Y), I assume it means "X and Y
are siblings".
Here, it's not a relation but a command.
It is a really good idea to make commands *obviously*
commands by making their names be verb phrases. (This
has nothing to do with Prolog. It's counted as good
practice in every programming language.)
So
print_children_of(Father, Mother) :-
( child_father(Child, Father),
child_mother(Child, Mother),
write(Child), nl,
fail
; true
).
Now the pattern ( P, Q, fail ; true) is common enough
that it has a name, and SWI supports that. And the
pattern write(X), nl is common enough that _it_ has
a name, and SWI supports that.
child_father_mother(Child, Father, Mother) :-
child_father(Child, Father),
child_mother(Child, Mother).
print_children_of(Father, Mother) :-
foreach(
child_father_mother(Child, Father, Mother),
writeln(Child) ).
and now it's pretty hard to misunderstand.