如何在prolog中递归更改列表中的元组?

时间:2011-11-19 15:59:49

标签: list recursion prolog tuples

我有以下格式的列表:

[(index, count, color),(index+1,newcount,othercolor),...]

我想要一个带有索引的有序列表,用该索引更改元组的计数值。

到目前为止我所做的是:

play(Index,[(Index,Count,Color)|T], [(Index,NewCount,Color)|T]):-

    NewCount is Count + 1.


play(Index,[Tuple|T],[Tuple|T]):-

    play(Index,T,T).

它只是给了我......

有什么建议吗?

Thanx任何答案!

2 个答案:

答案 0 :(得分:0)

由于你想创建一个不同的列表,你不能说在谓词的第二个子句中会是相同的。相反,您应该为新尾部使用新变量。类似的东西:

play(Index,[(Index,Count,Color)|T], [(Index,NewCount,Color)|T]):-
    NewCount is Count + 1.


play(Index,[Tuple|T1],[Tuple|T2]):-    
    play(Index,T1,T2).                

答案 1 :(得分:0)

因为您知道它已经排序,所以如果Index不在列表中,您可以提早失败。

play(Index,[(Index,Count,Color)|T], [(Index,NewCount,Color)|T]) :-
  NewCount is Count + 1.
play(Index,[(IndexT,_,_)|_], _) :-
  Index < IndexT, !, fail.
play(Index,[Tuple|T1],[Tuple|T2]) :-
  play(Index,T1,T2).

允许上面的低效率,您可能会对使用标准内置函数进行列表操作的可能解决方案感兴趣。

play_bt(Index, Old, New) :-
  append(Left, [(Index, Count, Color)|Rest], Old),
  NewCount is Count + 1,
  append(Left, [(Index, NewCount, Color)|Rest], New).