序言 - 参数不够实例 [英] Prolog - Arguments are not sufficiently instantiated

查看:203
本文介绍了序言 - 参数不够实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个小程序,它计算列表中的很多元素是如何不是数字。
这里是我的code:

I am writing a little program which counts how many elements in a list are not numbers. Here is my code:

not_number([],0).
not_number([X|T],R):- 
    not(number(X)),
    R1 is R+1,  
    not_number(T,R1). 

not_number([_|Tail],Result):-
    not_number(Tail,Result).  

如果我执行code是这样的:

If I execute code like this :

?- not_number([1,2,3,5], R).

我得到了R = 0(因为它应该是)

I am getting that R = 0 (as it should be)

R = 0.

但是,如果我把一个角色列表:

But if I put a character in the list:

?- not_number([1,2,3,5,a], R).

然后我得到这个错误:

then I am getting this error:

ERROR: not_number/2: Arguments are not sufficiently instantiated
   Exception: (10) not_number([a], _G247) ? 

有人能解释什么是错用code?我是新来的序言。

Can someone explain whats wrong with code? I am new to prolog.

推荐答案

您的问题是,在这样的算术计算:

Your problem is that in arithmetic computation like this:

A是B

在右侧(B)一切都要已知的。没有变数存在。

everything on the right side (B) has to be already known. No variables there.

您可以做这样的事情:

not_number(X, Y) :- not_number(X, Y, 0).
not_number([], Y, Y).
not_number([H|T], Y, Z) :-
    \+ (number(H)), 
    Z1 is Z+1,
    not_number(T, Y, Z1).

not_number([H|T], Y, Z) :-
    number(H),
    not_number(T, Y, Z).

(本测试code现在,它的工作原理)。

(tested this code now, it works).

现在第三个参数是累加器。它计算多少不是号码有。当列表是空的,这第三个参数是统一的第二个,并且变得正确答案。

Now the third argument is an accumulator. It counts how many not-numbers there are. When the list is empty, this third argument is unified with the second one and it becomes the proper answer.

序言,有机会的时候,将通过所有可能的路由。如果你做这样的事情:

Prolog, when given the chance, will go through all the routes possible. If you do something like this:

cat(adam).
cat(eve).

,然后问:

?- cat(X).

您可以得到两个答案:X =亚当和X =前夜。
它适用于你的code太:注意,当列表的头是不是一个数字,你仍然可以做到这一点:

You could get both answers: X = adam and X = eve. It applies to your code too: notice that when the head of the list is not a number, you can still do this:

not_number([_|Tail],Result):-
    not_number(Tail,Result).  

这给你不想要的答案。你必须切断不感兴趣你的路由。在这种情况下,我想补充

which gives not the answer you would like. You have to cut off the routes that don't interest you. In this case, I would add

number(Head).

要确保我们跳过列表中的一个元素,而不由1增加计数器只在此元素不是一个数字。

to ensure that we skip an element in a list without increasing the counter by 1 only when this element is not a number.

要执行的Prolog找到一些其他的结果,必须preSS;键盘上的(就像这个亚当和夏娃的例子)。

To enforce Prolog to find some other results, you must press ";" on your keyboard (like in this adam and eve example).

这篇关于序言 - 参数不够实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆