开发者

Understanding this prolog implementation of head

head([Y],Y):-!.

head([X|XS],X).

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

开发者_如何学运维

What does the first clause mean? Is it a cut? Why?


The implementation of head/2 is simply:

head([X | _], X).

Note that the underscore here means "zero or more elements that we don't care about".

There is no need to single out the case where the list has only one element (and then use a cut).


The first clause means if you only have one element in the list its true that (Y) will have the head. So yes it is a cut because it tells prolog to stop looking for answers if its successful up to that point. The second clause then expands on having more than one element in the list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜