开发者

Pascal's triangle in Prolog

开发者 https://www.devze.com 2022-12-11 06:29 出处:网络
I have written a function for returning the next row in Pascal\'s triangle given the current row: pascal_next_row([X],[X]).

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 ha开发者_Go百科ve 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]


Do the base case, N > 0 cancels your calculation...

pascalA(N,R,_Row):-
 N > 0, %% this evaluates to false so the calculation gets canceled
 M is N-1,
    next_row([0|R],NR),
    pascalA(M,NR,NR).

pascalA(0,R,R). %% this should be the base case... hope I got it correct...

pascalA(N,R,_Row):-
 M is N-1,
    next_row([0|R],NR),
    pascalA(M,NR,_Row).


You need a base case for pascalA where N = 0.

0

精彩评论

暂无评论...
验证码 换一张
取 消