go :- match(Mn,Fn),
write('--Matching Result--'),
nl,
write(Mn),
write(' match with '),
write(Fn),
match(Mn1,Fn1).
person(may,female,25,blue).
person(rose,female,20,blue).
person(hock,male,30,blue).
person(ali,male,24,blue).
match(Mn,Fn):-person(Fn,'female',Fage,Fatt),
person(Mn,'male',Mage,Matt),
Mage>=Fage,
Fatt=Matt.
Hi,this is my code...but it's only can show the 1 output...but there are 3 pair of matching in match(X,Y).how to show them all in my go function.
Thank you
output in Prologwrite(X) which writes the term X to the current output stream (which means the window on your workstation unless you have done something fancy). print(X, …) which writes a variable number of arguments to the current output stream.
writeln( +Term ) Equivalent to write(Term), nl. . The output stream is locked, which implies no output from other threads can appear between the term and newline.
1. print all elements of a list ?-print_list([a,b,c]). a b c print_list([]):-nl. %nl = newline print_list([H|T]):-write(H),write(' '),print_list(T).
We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU prolog, it supports only the ASCII value.
You get all your matches if you force backtracking, usually by entering ;
(e.g. in SWI Prolog). But you also see that you are getting unnecessary outputs true
. This is because the last clause in go
is match(Mn1,Fn1)
. This clause succeeds three times and binds the variables Mn1,Fn1
but then only true
is output, because you do not write()
after that clause. The fourth time match(Mn1,Fn1)
fails and by backtracking you come back to the first clause match(Mn,Fn)
that matches, the match is output, etc.
You surely do not want to have this behavior. You should remove the last clause match(Mn1,Fn1)
in go
. Now by pressing ;
you get the 3 matches without any output true
in between.
But what you likely want is that the program does the backtracking. To achieve this, you just need to force backtracking by adding false
as the last clause. To get proper formatting of the output, use the following program. The last clause go2.
is added to get true
at the very end.
go2 :- write('--Matching Result--'), nl,
match(Mn,Fn),
write(Mn), write(' match with '), write(Fn), nl,
fail.
go2.
This technique is called failure driven loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With