删除指定索引处的元素,如果给出负面的返回未触及的列表,则为0作为索引
嗨,我真的需要解决这个序言问题的帮助。我想在指定的索引上删除一个元素,但只有在给出大于0的索引时。如果索引为0或更小时,我只想将列表返回未触及的列表。
例如:
delete(List,Index,NewList).
?-L=[1,2,3,4],delete(L,2,L2),write(L2).
L2 = [1,3,4]
for< = 0:
delete(List,Index,NewList).
?-L=[1,2,3,4],delete(L,-1,L2),write(L2).
L2 = [1,2,3,4]
我设法使用以下代码处理了第一个情况。
remove([_|T], 1, T).
remove([H|T1], N, [H|T2]):-
N > 1,
I is N - 1,
remove(T1, I, T2).
我尝试使用Prologs If-Else等效语法,但无法使其正常工作。
编辑:非常感谢您的回复!我没有意识到我错过了另一个案件。
Hi I really am needing help with this Prolog problem. I want to delete an element at a specified index but only when given an index that is greater than 0. If the index is 0 or less, I would like to just return the list untouched.
For example:
delete(List,Index,NewList).
?-L=[1,2,3,4],delete(L,2,L2),write(L2).
L2 = [1,3,4]
for <= 0:
delete(List,Index,NewList).
?-L=[1,2,3,4],delete(L,-1,L2),write(L2).
L2 = [1,2,3,4]
I have managed to handle the first case using the following code.
remove([_|T], 1, T).
remove([H|T1], N, [H|T2]):-
N > 1,
I is N - 1,
remove(T1, I, T2).
I attempted using prologs if-else equivalent syntax but was not able to get it working.
EDIT: Thank you so much for the responses! I did not realize I was missing another case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需要在谓词定义中包含一个基本案例:
示例:
You just need to include one more base case in the predicate definition:
Examples:
您只需要另一个规则即可处理
n =&lt; 0
:You just need another rule for handling
N =< 0
: