生成列表-几何级数 [英] Generate list - geometric progression
问题描述
我想使用带有4个参数的谓词生成几何级数列表-生成级数的列表,该列表的长度,起始元素以及级数的乘数.到目前为止,我所做的只是只有一个3参数谓词来生成几何级数而不会停止:
I'd like to generate a geometric progression list using a predicate with 4 parameters - the list where the progression will be generated, the length of this list, the start element, and the multiplier of the progression. What I've done so far is having only a 3-parameter predicate to generate the geometric progression without stopping :
gengeom([X],X,_).
gengeom([H|Tail],H,Q):-X is H*Q,gengeom(Tail,X,Q).
此查询为我提供了开始元素1和乘数2的所有进度:
And this query gives me all progressions with start element 1 and multiplier 2 :
?-gengeom(L,1,2),write(L),nl,fail.
谁能帮我写出我真正想拥有的4参数谓词(在列表的长度变为某个数字后,它会停止生成更多数字)?
Can anyone help me write the 4-parameter predicate I'd really like to have (that stops generating any more numbers after the length of the list has become a certain number) ?
推荐答案
仅添加一个倒数参数将起作用,并且将保留代码的漂亮生成属性:
just adding a countdown parameter will work, and will preserve the nice generative property of your code:
gengeom([X],X,_,_).
gengeom([H|Tail],H,Q,N) :- N>1, M is N-1, X is H*Q, gengeom(Tail,X,Q,M).
?- gengeom(L,1,2,3).
L = [1] ;
L = [1, 2] ;
L = [1, 2, 4] ;
false.
当然,您可以使用findlog/3(Prolog的列表生成器")使结构更紧凑:
of course, you could get somewhat more compact using findall/3, the Prolog 'list generator':
gengeom(L,H,Q,N) :-
findall(V, (between(H,N,M), V is Q**(M-1)), L).
但是此代码段(类似于@ joel76'帖子)将仅构建最终"列表...
but this snippet (similar to @joel76' post) will build just the 'final' list...
这篇关于生成列表-几何级数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!