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

查看:19
本文介绍了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]

我不知道该怎么做.谢谢你的帮助!洛伊克.

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 运算符来不到达第三个后备子句.

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天全站免登陆