views:

101

answers:

3

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]
A: 

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

starblue
A: 

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
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]`
jsrs
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
just using `pascalA(0,R,R).` should work...
egon
+1  A: 

Maybe you should be asking your professor for help. I'm pretty sure asking for outside help is against your university's honor code.

labelreader