Prolog 中的帕斯卡三角形
我编写了一个函数,用于在给定当前行的情况下返回帕斯卡三角形中的下一行:
pascal_next_row([X],[X]).
pascal_next_row([H,H2|T],[A|B]):-
pascal_next_row([H2|T],B),
A is H + H2.
我希望能够找到三角形中的第 n 行,例如 pascal(5,Row)
, 行=[1,5,1,0,1,0,5,1]
。我有这个:
pascal(N,Row):-
pascalA(N,[1,0],Row).
pascalA(N,R,_Row):-
N > 0,
M is N-1,
next_row([0|R],NR),
pascalA(M,NR,NR).
显然 Row
应该是 n==0
之前找到的最后一个。我怎样才能退货?我尝试使用 is
关键字,即 Row is NR
但显然这是不允许的。有什么帮助吗?
尝试在列表上使用 is
会让我:
! Domain error in argument 2 of is/2
! expected expression, but found [1,4,6,4,1,0]
! goal: _23592586 is[1,4,6,4,1,0]
I have written a function for returning the next row in Pascal's triangle given the current row:
pascal_next_row([X],[X]).
pascal_next_row([H,H2|T],[A|B]):-
pascal_next_row([H2|T],B),
A is H + H2.
I want to be able to find the nth row in the triangle, e.g. pascal(5,Row)
, Row=[1,5,1,0,1,0,5,1]
. I have this:
pascal(N,Row):-
pascalA(N,[1,0],Row).
pascalA(N,R,_Row):-
N > 0,
M is N-1,
next_row([0|R],NR),
pascalA(M,NR,NR).
Obviously Row
should be the last one found before n==0
. How can I return it? I tried using the is
keyword, i.e. Row is NR
but that isn't allowed, apparantly. Any help?
Trying to use is
on lists gets me:
! Domain error in argument 2 of is/2
! expected expression, but found [1,4,6,4,1,0]
! goal: _23592586 is[1,4,6,4,1,0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
做基本情况,
N > 0
取消您的计算...Do the base case,
N > 0
cancels your calculation...您需要 pascalA 的基本情况,其中 N = 0。
You need a base case for pascalA where N = 0.