Understanding this prolific realization of the head

head([Y],Y):-!. head([X|XS],X). 

I understand that the head of the list is stored in the variable X.

What does the first sentence mean? Is this a cut? Why?

+4
source share
2 answers

The first sentence means that if you have only one item in the list, it means that (Y) will have a head. So yes, this is an abbreviation because it tells the prologue to stop searching for answers if it is successful up to this point. The second sentence is then expanded to include more than one item in the list.

+1
source

The implementation of head/2 is simple:

 head([X | _], X). 

Note that the underscore here means "zero or more elements that we do not need."

There is no need to highlight the case when there is only one item in the list (and then use cut).

+3
source

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


All Articles