Prolog,如何在 write() 中显示多个输出 [英] Prolog, how to show multiple output in write()

查看:50
本文介绍了Prolog,如何在 write() 中显示多个输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

go :- match(Mn,Fn),write('--匹配结果--'),NL,写(锰),写('匹配'),写(Fn),匹配(Mn1,Fn1).人(可能,女性,25,蓝色).人(玫瑰,女性,20,蓝色).人(霍克,男性,30,蓝色).人(阿里,男性,24,蓝色).match(Mn,Fn):-person(Fn,'female',Fage,Fatt),人(锰,'男',法师,马特),法师>=法格,脂肪=马特.

这是我的代码...但它只能显示 1 个输出...但是 match(X,Y) 中有 3 对匹配.如何在我的 go 函数中显示它们.

谢谢

解决方案

如果您强制回溯,通常通过输入 ;(例如在 SWI Prolog 中),您将获得所有匹配项.但是你也看到你得到了不必要的输出true.这是因为 go 中的最后一个子句是 match(Mn1,Fn1).这个子句成功了 3 次并且绑定了变量 Mn1,Fn1 但是只输出了 true,因为你没有在那个子句之后 write().第四次 match(Mn1,Fn1) 失败,通过回溯你回到第一个匹配的子句 match(Mn,Fn),匹配被输出,等等.

你肯定不想有这种行为.您应该删除 go 中的最后一个子句 match(Mn1,Fn1).现在按 ; 你会得到 3 个匹配,中间没有任何输出 true.

但您可能想要的是程序进行回溯.为此,您只需要通过添加 false 作为最后一个子句来强制回溯.要获得正确的输出格式,请使用以下程序.添加最后一个子句 go2. 以在最后获得 true.

go2 :- write('--Matching Result--'), nl,匹配(锰,Fn),写(Mn), 写('匹配'), 写(Fn), nl,失败.去2.

这种技术称为故障驱动循环.

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

解决方案

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.

这篇关于Prolog,如何在 write() 中显示多个输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆