从列表列表中删除项目
Remove Item from List of Lists
我有一个列表,其中包含具有 ID、姓名和性别的记录。我试图让用户传入 Id(整数)或名称(字符串),然后删除该记录,但它什么也没做。
这是我的:
choice(5,X) :-
write('\tEnter an ID or Name:'),
read(Item),
rem(Item, X, X2),
menu(X2).
我的移除是:
rem(Item, [], []) :- write("List is empty.").
rem(Item, [[Item,RT]|L],L).
rem(Item, [[ID, Item|PT]|L]|L).
rem(Item, [X|XT],[X|YT]) :- rem(Item, XT, YT).
但是当我 运行 它时,它只是给了我一个整数列表。
任何帮助将不胜感激!
您的代码(几乎)工作正常。
你刚刚在第三条规则中有一个错字:你写了一个 |
而不是 ,
,并且 prolog 解释器让你知道:
Warning: user://1:18:
Clauses of (rem)/3 are not together in the source-file
您可能想要删除 write("List is empty."),因为该规则不仅在您尝试从空列表中删除项目时匹配,而且它也是递归删除的基本情况。它打印数字是因为您为它提供了一个字符串 ("abc") 而不是一个原子 ('abc')。将 write('abc')
的结果与 write("abc")
的结果进行比较。
此外,您需要在删除规则中进行削减,因为如果该项目存在于列表中,您想要删除它,并且您对从该选择点回溯产生的其他解决方案不感兴趣。
rem(Item, [], []).
rem(Item, [[Item,RT]|L],L) :- !.
rem(Item, [[ID, Item|PT]|L],L) :- !.
rem(Item, [X|XT],[X|YT]) :- rem(Item, XT, YT).
测试:
?- rem(x, [[a,3],[b,4],[remove_me,x,6],[d,8]], X).
X = [[a, 3], [b, 4], [d, 8]].
可能是我误解了问题,但我认为
rem(Item, L_In, L_Out) :-
select([Item|_], L_In,L_Out);select([_,Item|_], L_In, L_Out).
完成任务。
我有一个列表,其中包含具有 ID、姓名和性别的记录。我试图让用户传入 Id(整数)或名称(字符串),然后删除该记录,但它什么也没做。
这是我的:
choice(5,X) :-
write('\tEnter an ID or Name:'),
read(Item),
rem(Item, X, X2),
menu(X2).
我的移除是:
rem(Item, [], []) :- write("List is empty.").
rem(Item, [[Item,RT]|L],L).
rem(Item, [[ID, Item|PT]|L]|L).
rem(Item, [X|XT],[X|YT]) :- rem(Item, XT, YT).
但是当我 运行 它时,它只是给了我一个整数列表。 任何帮助将不胜感激!
您的代码(几乎)工作正常。
你刚刚在第三条规则中有一个错字:你写了一个 |
而不是 ,
,并且 prolog 解释器让你知道:
Warning: user://1:18:
Clauses of (rem)/3 are not together in the source-file
您可能想要删除 write("List is empty."),因为该规则不仅在您尝试从空列表中删除项目时匹配,而且它也是递归删除的基本情况。它打印数字是因为您为它提供了一个字符串 ("abc") 而不是一个原子 ('abc')。将 write('abc')
的结果与 write("abc")
的结果进行比较。
此外,您需要在删除规则中进行削减,因为如果该项目存在于列表中,您想要删除它,并且您对从该选择点回溯产生的其他解决方案不感兴趣。
rem(Item, [], []).
rem(Item, [[Item,RT]|L],L) :- !.
rem(Item, [[ID, Item|PT]|L],L) :- !.
rem(Item, [X|XT],[X|YT]) :- rem(Item, XT, YT).
测试:
?- rem(x, [[a,3],[b,4],[remove_me,x,6],[d,8]], X).
X = [[a, 3], [b, 4], [d, 8]].
可能是我误解了问题,但我认为
rem(Item, L_In, L_Out) :-
select([Item|_], L_In,L_Out);select([_,Item|_], L_In, L_Out).
完成任务。