1

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]
blork
  • 2,150
  • 6
  • 26
  • 45

2 Answers2

0

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

starblue
  • 55,348
  • 14
  • 97
  • 151
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).
Egon
  • 1,705
  • 18
  • 32
  • I can't seem to use the `is` function on lists. I'm using SICStus, and I get the error `! 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]` – blork Nov 15 '09 at 15:35
  • oh sorry... I forgot it was a list... I was writing this thing from memory (read: didn't test)... I think substituting `is` with `=` might work... – Egon Nov 15 '09 at 19:24