删除指定索引处的元素,如果给出负面的返回未触及的列表,则为0作为索引

发布于 2025-01-23 07:13:06 字数 567 浏览 0 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

茶底世界 2025-01-30 07:13:06

您只需要在谓词定义中包含一个基本案例

remove(L, N, L) :-
    N =< 0.
remove([_|T], 1, T).
remove([H|T1], N, [H|T2]):-
    N > 1,
    I is N - 1,
    remove(T1, I, T2).

示例:

?- L = [one, two, three, four], remove(L, 2, R).
L = [one, two, three, four],
R = [one, three, four] ;
false.

?- L = [one, two, three, four], remove(L, -1, R).
L = R, R = [one, two, three, four] ;
false.

You just need to include one more base case in the predicate definition:

remove(L, N, L) :-
    N =< 0.
remove([_|T], 1, T).
remove([H|T1], N, [H|T2]):-
    N > 1,
    I is N - 1,
    remove(T1, I, T2).

Examples:

?- L = [one, two, three, four], remove(L, 2, R).
L = [one, two, three, four],
R = [one, three, four] ;
false.

?- L = [one, two, three, four], remove(L, -1, R).
L = R, R = [one, two, three, four] ;
false.
甜味超标? 2025-01-30 07:13:06

您只需要另一个规则即可处理n =&lt; 0

remove(L, N, L) :-
    N =< 0.

remove([_|T], 1, T).

remove([H|T1], N, [H|T2]):-
    N > 1,
    I is N - 1,
    remove(T1, I, T2).

You just need another rule for handling N =< 0:

remove(L, N, L) :-
    N =< 0.

remove([_|T], 1, T).

remove([H|T1], N, [H|T2]):-
    N > 1,
    I is N - 1,
    remove(T1, I, T2).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文