Prolog - 检查列表是否为空[]

时间:2015-11-13 00:14:33

标签: list prolog

我只想弄清楚如何检查一个列表是否为空,我把一些检查列表长度的东西放在一起,另外还要检查列表是否为空。

% Gives the length of a list.
listlength([]     , 0 ).
listlength([_|Xs] , L ):- 
    listlength(Xs,N), 
    L is N+1. 

% checks to see that the length of the list is greater than or equal to 3 and not empty.
check_length( [] ).
check_length( L  ):-
    listlength(L, Len),
    Len >= 3,
    L \== [].    %This is the bit of code I'm having problems with 
                  it should be false if the list is just [] or empty.

我是学生,所以我不一定需要一个直接的答案我只是想弄清楚我做错了什么。

5 个答案:

答案 0 :(得分:4)

您不需要明确测试L是否为空列表;它的长度> 0确立了。

您已经知道如何测试列表不为空,因为您在var Promise = require('bluebird'); var getRequest = Promise.promisify(require('http').get); this.addMenu = function(currentMerchant) { var id = currentMerchant.id; function getMenu(id) { var deferred = Q.defer(); var url = 'https://api.delivery.com/merchant/'+id+'/menu?client_id=xyz'; return getRequest(url); } this.data.menu = getMenu(id) .then(function(response) { return JSON.parse(response.body); }) .catch(function (err){ console.log("Something went wrong with menu GET request: " + err); }); console.log(this.data.menu); }; 中使用了它:listLength(即L=[_|_]是一个至少包含1个元素的列表)。

答案 1 :(得分:1)

问题是“如何检查列表是否为空”。根据定义,空列表是没有元素的列表,即[]列表。您只需检查一下您的列表是否与之结合即可。

答案 2 :(得分:1)

另一种选择,如果您的使用范围有限:

is_empty(List):- not(member(_,List)).

检查给定列表中是否有成员,并返回否定值。

[] =>没有成员,为空。

[foo] =>成员存在,不为空。

答案 3 :(得分:0)

router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, 
Content-Type, Accept, pwd, email");
next();
});

答案 4 :(得分:0)

对我有用的是:

empty_List(List):-列表= []。

相关问题