如何使用PROLOG中的索引替换列表的元素 [英] How can I replace an element of a list using an index in PROLOG

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

问题描述

我需要这样做:

replace(L,P,E,R),其中L是当前列表,P是元素要插入的位置,E是要插入的元素,R是返回的新列表.

replace(L,P,E,R), where L is the current list, P is the position where the element will be insert, E is the element to insert and R is the return, the new list.

示例:

L = [1,2,3,4,5],
replace(L,2,'@',R).
R = [1,2,'@',4,5]

我尝试了此操作,但没有任何反应,列表连续不变:

I tried this, but nothing happens, the list continuous to be the same:

replaceInThePosition([_|T],1,E,[['1',E]|T]).
replaceInThePosition([H|T],P,E,[H|R]) :-
    P > 0, NP is P-1, replaceInThePosition(T,NP,E,R), !.

推荐答案

您不远.

您可以尝试

replaceInThePosition([_|T],0,E,[E|T]).
replaceInThePosition([H|T],P,E,[H|R]) :-
    P > 0, NP is P-1, replaceInThePosition(T,NP,E,R).

我的意思是:

1)而不是第一个子句中的1(或第一个子句中的1,而第二个子句中的P > 1);但是在这种情况下,您是从replaceInThePosition([1, 2, 3, 4, 5], 2, '@', R)中统一R = [1, @, 3, 4, 5]而不是R = [1, 2, @, 4, 5])

1) 0 instead 1 in the first clause (or 1 in the first clause but P > 1 in the second one; but in this case from replaceInThePosition([1, 2, 3, 4, 5], 2, '@', R) you unify R = [1, @, 3, 4, 5], not R = [1, 2, @, 4, 5])

2)[E|T]表示第一个子句中的最后一个参数,而不是[['1',E]|T]

2) [E|T] for the last ergument in the first clause, not [['1',E]|T]

3)在第二个子句的末尾没有剪切(没有!)(没有必要:P为零时第一个子句i; P > 0时为secon一个;因此它们是互斥的

3) no cut (no !) at the end of the second clause (there is no need: the first clause i when P is zero; the secon one when P > 0; so they are mutually exclusive

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

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