在列表Prolog中找到2的幂 [英] Find powers of 2 in a list Prolog

查看:74
本文介绍了在列表Prolog中找到2的幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Prolog(SWI Prolog)中创建一个列表,并检查哪些数字是2的幂,然后第二次查找该列表中特定数字的次数(在此示例中,我试图查找多少个数字)乘以数字3在列表中). 例如,如果您询问

I'm trying to create a list in Prolog (SWI Prolog) and check which numbers are powers of 2 and second find how many times a specific number is in the list (in this example I'm trying to find how many times the number 3 is in the list). For a example, if you ask

?- check([0,2,3,-5,-2,1,8,7,4], MULT2, THREE).

您应该看到

MULT2=[2,8,4] 
THREE=1 

我的第一个尝试找到解决方案的方法是搜索带有head的列表,并使用head mod 2 = 0来查找所有为2的幂的数字,但是出了点问题,我只得到"false"作为答案.

My first try to find a solution is to search the list with head and doing head mod 2 = 0 to find all numbers which are powers of 2, but something went wrong and I only get "false" as an answer.

推荐答案

在这里,您可以通过逻辑上纯净的方式找到二的幂"!

Here's how you can find the "powers of two" in logically-pure way!

使用 4.3.5,library(reif)library(clpz):

Using sicstus-prolog 4.3.5, library(reif) and library(clpz):


:- use_module([library(reif), library(clpz)]).

power_of_two_t(I, T) :-
   L #= min(I,1),
   M #= I /\ (I-1),
   call((L = 1, M = 0), T).      % using (=)/3 and (',')/3 of library(reif)

使用元谓词 tfilter/3 power_of_two_t/2结合使用的示例查询 1 :

Sample query1 using meta-predicate tfilter/3 in combination with power_of_two_t/2:

?- tfilter(power_of_two_t, [0,2,3,-5,-2,1,8,7,4], Ps).
Ps = [2,1,8,4].                  % succeeds deterministically

这是一条由注释建议的更一般的查询:

Here's a more general query suggested by a comment:

?- tfilter(power_of_two_t, [X], Ps).
   Ps = [X], 0#=X/\_A, _A+1#=X, X in 1..sup, _A in 0..sup
;  Ps = [], dif(_A,0), _A#=X/\_B, _B+1#=X, X in 1..sup, _B in 0..sup
;  Ps = [], dif(_A,1), _A#=min(X,1), _B#=X/\_C, _C+1#=X, X#>=_A, _A in inf..1.


脚注1:整理了上面显示的答案序列,以表明呼叫的确定性.


Footnote 1: The answer sequences shown above were brushed up to indicate the determinism of calls.

脚注2:要重现结果,请使用call_det/2,其定义如下:

Footnote 2: To reproduce the results use call_det/2 which is defined like this:


call_det(G_0, Det) :-
   call_cleanup(G_0, Flag = set),
   (  nonvar(Flag)
   -> Det = true
   ;  Det = false
   ).

这篇关于在列表Prolog中找到2的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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