首页 > 解决方案 > 尝试在 Prolog 中编写代码,我输入一个包含字符串和数字的列表,我想获得它们之间的最大数字

问题描述

这就是我的列表应该是什么样子,[[item(tag(""),data(""),ValidBit,N)|T]但我只关心列表中的最后一个 N 并且我想获得它们之间的最大数量。

我最好的情况是max_l([don't care,don't care,don't care,N)],N).

我不知道其余的应该如何工作。

标签: listprologmax

解决方案


我将冒险并假设有问题的数据是一个item/3术语列表:

[
  item(_,_,N1),
  item(_,_,N2),
  item(_,_,N3),
  . . .
]

item/3并且我们勇敢的冒险者想要找到列表中每个术语的第三个参数的最大值。

假设,这样的事情会起作用(不使用任何内置插件,因为这似乎也是一个合理的假设,即这是功课):

max_item_n( []                  , _   ) :- % if the list is empty
  !, fail.                                 %   there is no max value
max_item_n( [item(_,_,N)|Items] , Max ) :- % if the list is non-empty
  max_item_n_helper(Items,N,Max) .             seed the reducer with the value of the head and invoke it

max_item_n_helper( []                  , Max , Max ) .  % once the list is exhausted, we're done.
max_item_n_helper( [item(_,_,N)|Items] , T   , Max ) :- % otherwise...
  max(N,T,Max),                                         % determine the larger of N and T, and
  max_item_n_helper( Items, T1, Max )                   % recurse down on the tail
  .

max( N , T , N ) :- N > T, !.
max( N , T , T ) .

推荐阅读