Prolog - 参数没有充分实例化 [英] Prolog - Arguments are not sufficiently instantiated
问题描述
我正在编写一个小程序,它计算列表中有多少元素不是数字.这是我的代码:
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).
如果我执行这样的代码:
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).
然后我收到此错误:
ERROR: not_number/2: Arguments are not sufficiently instantiated
Exception: (10) not_number([a], _G247) ?
有人能解释一下代码有什么问题吗?我是 prolog 的新手.
Can someone explain whats wrong with code? I am new to prolog.
推荐答案
我正在写这个答案,因为最好的答案在 lurker 的论点未充分实例化#comment36639272_23815952">评论.我想让它显示为一个实际的答案.
I am writing this answer, because the best answer yet was in a comment by lurker. I want to have it show up as an actual answer.
您的代码不起作用,因为在 not_number([X|T],R)代码>.您的递归案例有点倒退.你想这样做:
Your code is not working, because you're doing R1 is R+1
when R
isn't instantiated in the case not_number([X|T], R)
. Your recursive case is strung a little backwards. You want to do this:
not_number([X|T],R):-
not(number(X)),
not_number(T,R1),
R is R1+1.
现在is
的右边在被调用时被实例化了.
Now the right side of the is
is instantiated when it is called.
这篇关于Prolog - 参数没有充分实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!