简体   繁体   English

如何递归地更改序言列表中的元组?

[英]how to recursively change a tuple inside a list in prolog?

I have a list in the following format: 我有以下格式的列表:

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

And I want, having an ordered list with an index given, change the count value of the tuple with that index. 而且我想给定索引的有序列表,用该索引更改元组的计数值。

What I've done so far is: 到目前为止,我所做的是:

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

    NewCount is Count + 1.


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

    play(Index,T,T).

It just gives me no... 它只是给我没有...

Any suggestions? 有什么建议么?

Thanx for any answer! 谢谢任何答案!

since you want to create a different list, you cannot say at the second clause of the predicate will be the same. 由于您要创建其他列表,因此您不能在谓词的第二个子句中说相同。 Instead, you should use a new variable for the new tail. 相反,您应该为新尾使用新变量。 Something like: 就像是:

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


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

Because you know it's sorted, you can fail early in case Index is not in the list. 因为您知道它已经排序,所以如果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).

Allowing the inefficiency above, you could be interested in a possible solution that uses standard builtins for list manipulation. 考虑到上面的低效率,您可能会对使用标准内置函数进行列表处理的解决方案感兴趣。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM