What is the difference between a list with anything ([_]) and anything (_)

I tried to do the following, if I have two lists: L1 and L2, I wanted the result (R) to be a β€œsubtraction” of L2 from L1.

Example:

L1 = [1,2,3] L2 = [2,3,4,5] R = [1] 

I was able to accomplish this, but I cannot say what the difference is between _ and [_] .

If I do this:

 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 a lie:

 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). 

I would suggest that a list containing anything [_] should work, since L2 will always be a list.

+6
source share
2 answers

Actually, _ matches only one variable and one variable. Here you want it to match 2, 3, 4, 5 (four variables). It's impossible. It can only match [2, 3, 4, 5] (list). You need to write [_|_] so that the head and tail coincide ( [2|[3, 4, 5]] )

Or [_, _, _, _, _, _, ...] with the number _ being the exact number of elements in your list so that each individual element is appropriately mapped to an anonymous variable.

The most important thing to remember is that _ is just a normal variable. If you have problems remembering it, just explicit names, such as _Head or _Accumulator , so you understand when you write your code that the thing you are manipulating is actually a variable, only you are not interested (a variable starting with _ will not give a warning about a single variable, at least in swi-pl, so they can be used instead of _ for better general clarity).

Edit : Another way to say that in your title you think _ is something. But everything can be nothing, and everything can be much. _ can be only one. This is why this does not work:]

+8
source

_ is something ... foo, [1,2], bar (42, foo [2,3,7]), etc.
[_] is a list that has exactly one element, which can be any

in your example, if L2 contains more than one element (or an empty list), then it will not match [_]

+4
source

Source: https://habr.com/ru/post/904038/


All Articles