我有一些事实,比如:
motherboard('name', price, 'price range', score).我需要拿最好的主板按分数,所以我想我应该使用findall,但我不知道如何按分数排序(desc顺序),并采取第一个!你能帮帮我吗?
编辑-@ EDIT 27815解决方案:
motherboard('Gigabyte B360M Aourus Gaming 3', 86, 'low_range', 3).
motherboard('MSI B350M Mortar', 93, 'low_range', 4).
motherboard('ASUS ROG Strix B350\u002DF', 114, 'middle_range', 6).
motherboard('MSI Z370 Tomahawk', 139, 'middle_range', 7).
motherboard('Gigabyte Aorus AX370 Gaming K7', 169, 'high_range', 8).
setof(Score-Nome,motherboard(Nome, Price,Price_range, Score),Pairs), sort(1,@>,Pairs,Sorted),
write(Pairs),
nl,
write(Sorted).结果是:3G的B360M Aourus游戏3对和排序,它的结尾点,我可以按;有更多的解决方案,为什么不打印它们全部在一起?无论如何,对对和排序的顺序是相同的。
@PauloMoura解决方案-与以前解决方案的数据相同:setof(得分-Nome,主板(Nome,Price,Price_range,Score),PauloMoura解决方案),最后一组(对,BestMotherboard),写(BestMotherboard)。
我明白了:
?- start.
3-Gigabyte B360M Aourus Gaming 3
true ;
4-MSI B350M Mortar
true ;
6-ASUS ROG Strix B350-F
true ;
7-MSI Z370 Tomahawk
true ;
8-Gigabyte Aorus AX370 Gaming K7
true.发布于 2018-06-10 08:57:18
给予:
motherboard('thing1', price, 'price range', 5).
motherboard('thing2', price, 'price range', 4).
motherboard('thing3', price, 'price range', 3).
motherboard('thing4', price, 'price range', 2).
motherboard('thing5', price, 'price range', 1).我们可以询问:
?-setof(Score-Thing,motherboard(Thing,price,'price range',Scores),Pairs), sort(1,@>,Pairs,Sorted).
Pairs = [1-thing5, 2-thing4, 3-thing3, 4-thing2, 5-thing1],
Sorted = [5-thing1, 4-thing2, 3-thing3, 2-thing4, 1-thing5].setof/3对答案进行排序,但不是按您想要的顺序排序,因此,如果我们希望对整个列表进行排序,而不仅仅是排名第一,我们就需要使用sort/4。
或者,您也可以定义一个逆谓词(make 5 to -5等),并将其包含在setof/3调用中,以避免“排序两次”,但是您需要将排序列表重新转换以查看原始数字,如果有负值,这将无法工作。
发布于 2018-06-10 08:23:04
使用标准setof/3谓词而不是findall/3谓词将为您提供一个按升序排序的列表。然后,您可以遍历该列表,以获取最后一个元素,这将是主板与最好的分数。类似于:
...,
setof(..., ..., Motherboards),
last(Motherboards, BestMotherboard).last/2谓词是一个公共库谓词。
https://stackoverflow.com/questions/50781714
复制相似问题