我在Prolog中有以下代码:
designer(name("Ivan", "Ivanov"), "Bulgarian", 12, 11).
designer(name("John", "Turturro"), "Italian", 2, 9).
designer(name("John", "McLane"), "American", 32, 26).
designer(name("Roberto", "Turturro"), "Italian", 32, 8).
designer(name("Petar", "Petrov"), "Bulgarian", 32, 23).
designer_max_points(FirstName, LastName, Points) :-
designer(name(FirstName, LastName), _, _, Points),
not(designer(name(_,_), _,_, Points1), Points1 > Points).
我的目标是从每个设计师事实中获取最大分值(最后一个值)。
上述解决方案有效,但我不确定原因。我已经研究过 not 谓词,并且显然它的参数失败时会成功(例如? - not(2 = 3)。将返回true)。
但如果是这样的话:
designer_max_points(FirstName, LastName, Points) :-
designer(name(FirstName, LastName), _, _, Points),
designer(name(_, _), _,_, Points1),
Points > Points1.
...为什么这段代码不起作用?
答案 0 :(得分:0)
它不起作用,因为只有2个设计师的每个组合能够成功地完成约束。你想做的是这样的:
designer_max_points( Name, Surname , Points ) :-
findall(d(N,S,P) , designer(name(N,S),_,_,P) , Ds ) , % get the list of info you need
max_in_list(Ds,d(Name,Surname,Points)) % then scan it to find the desired value
.
max_in_list( [D|Ds],M) :- max_in_list(Ds,D,M) . % get find the max value in the list, invoke the worker predicate using the head of the list as the current max.
max_in_list( [] , M , M ) . % once the source list is exhausted, the current max is the final max
max_in_list( [d(N,S,P)|Ds] , d(Nm,Sm,Pm) , M ) :- % otherwise...
( P > Pm -> T1 = d(N,S,P) ; T1 = d(Nm,Sm,Pm) ) , % pick the new current max (T1),
max_in_list(Ds,T1,M) % then recurse down on the tail.
. % easy!
答案 1 :(得分:0)
它回答了另一个问题:
有没有设计师比其他设计师有更多的分数?
它将成功获得许多重复的答案,例如
name("Ivan", "Ivanov")
的积分高于name("John", "Turturro")
和name("Roberto", "Turturro")
,所以你应该得到两次
FirstName='Ivan', LastName='Ivanov', Points=11
依旧......