有任何内容([_])和任何内容(_)的列表有什么区别 [英] What is the difference between a list with anything ([_]) and anything (_)
问题描述
我试图完成以下任务,如果我有两个列表L1和L2,我希望结果(R)是从L1减去L2.
I was trying to accomplish the following, if I have two lists, L1 and L2, I wanted that the result (R) to be the "subtraction" of L2 from L1.
示例:
L1 = [1,2,3]
L2 = [2,3,4,5]
R = [1]
我能够做到这一点,但我不知道_
和[_]
有什么区别.
I WAS able to accomplish this but I can't tell what is the difference between _
and [_]
.
如果我这样做:
diferencia([],_,[]).
diferencia([X|Tail],L2,R):-
member(X,L2),
diferencia(Tail,L2,R).
diferencia([X|Tail],L2,[X|R]):-
not(member(X,L2)),
diferencia(Tail,L2,R).
它起作用了,如果我这样做,就会给我错误:
It works, if I do this, it gives me false:
diferencia([],[_],[]).
diferencia([X|Tail],L2,R):-
member(X,L2),
diferencia(Tail,L2,R).
diferencia([X|Tail],L2,[X|R]):-
not(member(X,L2)),
diferencia(Tail,L2,R).
我认为包含任何[_]
内容的列表都应该起作用,因为L2始终是列表.
I would assume a list containing anything [_]
should work since L2 will always be a list.
推荐答案
实际上,_
仅匹配一个变量和一个变量.在这里,您希望它与2, 3, 4, 5
(四个变量)匹配.不可以它只能匹配[2, 3, 4, 5]
(列表).您必须编写[_|_]
以便头部和尾部匹配([2|[3, 4, 5]]
)
Actually, _
matches one variable and one variable only. Here, you'd want it to match 2, 3, 4, 5
(the four variables). It can't. It can only match [2, 3, 4, 5]
(the list). You'd have to write [_|_]
so that the head and the tail are matched ([2|[3, 4, 5]]
)
或[_, _, _, _, _, _, ...]
,其中_
的数量是列表中项目的确切数量,以便每个元素都与匿名变量正确匹配.
Or [_, _, _, _, _, _, ...]
with the number of _
being the exact number of items in your list so that every single element is properly matched with an anonymous variable.
要记住的基本内容是_
只是一个普通变量.如果您在记住它时遇到麻烦,只需使用显式名称即可,例如_Head
或_Accumulator
,这样您就可以在编写代码时意识到,所操作的对象实际上是一个变量,只在乎它(变量开头至少在swi-pl中使用_
不会产生单例变量警告,因此可以使用它们代替_
以获得更好的整体清晰度.
The basic thing to remember is that _
is just a normal variable. If you have troubles remembering it, just explicit names, like _Head
or _Accumulator
, so that you do realize when you write your code that the thing you manipulate is actually a variable, only you do not care about it (variable starting with a _
won't produce a singleton variable warning, in swi-pl at least, so they're usable instead of _
for a better overall clarity).
编辑:另一种说法是,标题中您认为_
是任何东西.但是,任何事物都可以是虚无的,任何事物都可以是许多事物. _
只能是一件事.这就是为什么它不起作用:]
Edit : one other way to say it is that in your title, you think _
is anything. But anything can be nothing, and anything can be many things. _
can only be one thing. That's why it doesn't work : ]
这篇关于有任何内容([_])和任何内容(_)的列表有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!