Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog, how to show multiple output in write()

Tags:

prolog

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

like image 765
Adrian Avatar asked Sep 08 '11 14:09

Adrian


People also ask

How do you write output in Prolog?

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.

What is writeln in Prolog?

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.

How do I print a list in Prolog?

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

How do you write text in Prolog?

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.


1 Answers

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.

like image 152
Jiri Kriz Avatar answered Oct 10 '22 02:10

Jiri Kriz