Prolog:在指定索引处替换列表中的元素 [英] Prolog: replace an element in a list at a specified index

查看:146
本文介绍了Prolog:在指定索引处替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个Prolog谓词,该谓词可以替换指定索引处列表中的元素.

I'd like to have a Prolog predicate that can replace an element in a list at a specified index.

示例:

% replace(+List,+Index,+Value,-NewList).
?- L=[a,b,c,d], replace(L,1,z,L2).
L2 = [a,z,c,d]

我不知道该怎么做.谢谢你的帮助! Loïc.

I don't know how to do this. Thanks for your help! Loïc.

推荐答案

我将为您提供基本情况,我认为您应该能够轻松地进行递归情况:

I'll give you the base case, I think you should be able to do the recursive case with ease:

replace([_|T], 0, X, [X|T]).

现在操作已经解决了,我将添加递归案例:

Now that the op has solved it, I'll add the recursive case:

replace([H|T], I, X, [H|R]):- I > 0, I1 is I-1, replace(T, I1, X, R).

edit2:

这应该在@GeorgeConstanza在评论中提出要求时以超出范围的方式返回原始列表:

This should return the original list in an out of bounds situation as @GeorgeConstanza asks in the comments:

replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):- I > -1, NI is I-1, replace(T, NI, X, R), !.
replace(L, _, _, L).

如果有很好的边界替换,基本上是利用cut运算符来避免使用第三个fallback子句.

It's basically taking advantage of the cut operator to not get to the third fallback clause if there's a good in-bounds replacement.

这篇关于Prolog:在指定索引处替换列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆