简体   繁体   English

Prolog:数字列表

[英]Prolog: list of numbers

How can I generate a list of numbers from 1 to N, where N >= 0? 如何生成从1到N的数字列表,其中N> = 0?

Predicate: numbers(N, L). 谓词:数字(N,L)。

?-­ numbers(5,X).

X = [1, 2, 3, 4, 5].

?­- numbers(0,X).

X = [].

Use the built-in numlist/3 : 使用内置的numlist/3

?- numlist(1, 5, L).
L = [1, 2, 3, 4, 5].

?- numlist(1, 0, L).
false.

In SWI-Prolog you can use listing(numlist) to see how it has been implemented. 在SWI-Prolog中,您可以使用listing(numlist)来查看它是如何实现的。

Note that numlist/3 will never generate an empty list. 请注意, numlist/3永远不会生成空列表。 If you want that, then you need to write a simple wrapper that maps failure to an empty list. 如果你想要,那么你需要编写一个将失败映射到空列表的简单包装器。

You can use between to generate integers between to endpoints and then findall to collect them together. 您可以使用between生成到端点between整数,然后findall将它们收集在一起。 Try this predicate - 试试这个谓词 -

numbers(Count, List) :-
    findall(N, between(1,Count,N), List).

If you give Count anything <=0, between fails and this predicate will generate the empty list. 如果你给Count任何<= 0,则在失败之前,这个谓词将生成空列表。

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

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