Prolog(参数未实例化) [英] Prolog (arguments not instantiated)

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

问题描述

我正在写一个谓词,它将连续的元素(所有否定或肯定的元素)分为不同的组 像

I am writing a predicate that separates consecutive elements(all negative or positive) into different groups like

same([1,2,3,-1,-3,-2,4,5,6],X).
would output [[1,2,3],[-1,-3,-2],[4,5,6]]

我的代码在下面(仅正数部分):

and my code is below(only positive part):

same([],[]).  
same([H|T],[[X,Y,H]|Tail]):-
   X >= 0,
   H >= 0,
   same(T,[[X,Y]|Tail]).

Error message:ERROR: Arguments are not sufficiently instantiated

ERROR: In:
ERROR:    [9] _4652>=0
ERROR:    [8] sign_runs([2,2|...],[_4696,_4702|...]) at /Users/filepath:40
ERROR:    [7] <user>

有人可以帮忙吗?预先感谢.

Could somebody help? Thanks in advance.

推荐答案

调用相同([1,2,3,-1,-3,-2,4,5,6],X) .第二个子句被调用. H等于1,T等于[2,3,-1,-3,-2,4,5,6].

When you call same([1,2,3,-1,-3,-2,4,5,6],X). the second clause is called. H is instancied with 1, T with [2,3,-1,-3,-2,4,5,6].

因此,当调用 X> = 0 时,X是未知的.

So when X >= 0 is called, X is unknown.

您必须从列表的末尾开始工作,所以我们需要三件事:到达末尾时该做什么,之后要做什么以及如何到达列表末尾!

You must start the work from the end of the list, so we need three things, what do we do when we reach the end, what we do after, and how we reach the end of the list !

只有一个元素时,这很容易:

When there is only one element, it's easy :

same([X], [[X]]).

现在,当我们开始时很简单,我们就可以使用以下配置:

Now when we have got the start it's easysimple, we work with this configuration :

相同([H | T],[[X | T1] | Tail]).

相同([X],[[X]])开始,T表示为 [] ,同上表示 T1 尾巴.

From same([X], [[X]]), T is instancied with [], idem for T1 and Tail.

现在我们只需要检查乘积H * X 如果大于0,我们将H放在 [X | T1] 的开头,例如 [H,X | T1] ,如果没有,我们创建一个新列表 [[H],[X | T1] | Tail] .

Now we just have to check the product H*X If it's greater than 0 we put H in the head of [X|T1] e.g. [H,X|T1], if not we create a new list [[H],[X|T1]|Tail].

最后一件事,如果要到达列表的末尾.如果我们的朋友回想起

The last thing if to reach the end of the list. Recusion if our friend

same([H|T], Tail) :-
   same(T, Tail1),
   ...

现在我们可以编写整个代码:

Now we can write the whole code :

same([X],[[X]]).

same([H|T], Tail):-
    same(T, [[X| T1]|Tail1]),
    /* Bad answer for [1,2,0,-5] 
    ( H*X >= 0
    ->  Tail = [[H, X | T1] | Tail1]
    ;   Tail =  [[H], [X|T1] | Tail1]).
   */
   (   H >= 0
   ->  (X >= 0
       ->  Tail = [[H, X | T1] | Tail1]
       ;   Tail =  [[H], [X|T1] | Tail1])
   ;   (X < 0
       ->  Tail = [[H, X | T1] | Tail1]
       ;   Tail =  [[H], [X|T1] | Tail1])).

然后我们得到:

  ?- same([1,2,3,-1,-3,-2,4,5,6],X).
X = [[1, 2, 3], [-1, -3, -2], [4, 5, 6]] ;

这篇关于Prolog(参数未实例化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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