简体   繁体   English

序言:附加到列表的开头

[英]Prolog: Appending to the head of a list

How do I do the above? 我该如何做? Specifically, if I have a list like this: 具体来说,如果我有这样的列表:

List = [8, 9, 10]. % I know this using matching to assign the say that [8, 9, 10] = [8, 9, 10], thus making List contain [8, 9, 10]

Now if I try to append another variable to this existing list, how do I do this? 现在,如果我尝试将另一个变量附加到此现有列表中,该怎么做? I tried this: 我尝试了这个:

List = [7|List].

This will obviously not work (although I wish it did). 这显然将不起作用(尽管我希望如此)。 Then I tried this: 然后我尝试了这个:

List is [7|List].

Still nothing. 依然没有。 What can I do to append a variable to the head of a list? 如何将变量附加到列表的开头? If there is a way without using another function, but by manipulating this list, I will prefer, but all solutions are welcome. 如果有办法不使用其他功能,而是通过操纵此列表,我会更喜欢,但是欢迎所有解决方案。

Thanks 谢谢


Say I have a stub like so: 说我有一个像这样的存根:

stub(List):-
    List2 = [7|List],
    %% Do something recursively
    List = List2 %% How do I do thi part?

Found a solution, doesn't look very elegant but it works! 找到了一个解决方案,看起来不太优雅,但是可以正常工作!

stub(List, List2):-
    stub(List, [7|List2]), %% Some base case causes this recursion to stop
    %% Do something in the recursion
    List = List2 %% Finally do what I wanted to do

You need a new variable. 您需要一个新变量。 Thus List2 = [7|List] . 因此List2 = [7|List]

This is very odd compared to traditional, command oriented programming languages (also known as imperative pls), but it is the very essence of a declarative programming language, in particular a logic programming language. 与传统的面向命令的编程语言(也称为命令式编程语言)相比,这很奇怪,但这是声明性编程语言(尤其是逻辑编程语言)的本质。

There are a lot of implications behind this, it permits - for instance - to reason about a program in a much easier manner. 这背后有很多含义,例如,它允许以一种更容易的方式推理程序。

In any case, please do consult an introductory Prolog book like the Art of Prolog. 无论如何,请查阅Prolog入门书,例如Prolog的艺术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM