2

I must write a predicate to compute a row of Pascal's triangle. I try to write this with Binomial coefficient. In a first time, I managed to do it by displaying each result with writeln(). But I would like to save them in my list L. How can I do that ? Thank you

%coefficient(+N,+K,-R).
coefficient(_,0,1).
coefficient(N,N,1).
coefficient(N,K,R):-
    N>=K,
    K>0,
    N1 is N-1,
    K1 is K-1,
    coefficient(N1,K,R1),
    coefficient(N1,K1,R2),
    R is R1+R2.

/* Get a line from the coeff binomial */
%line(+E,-L)
line(N,L):-
    lineT(N,N,L).

lineT(_,0,_):-
    writeln(1).
lineT(N,K,L):-
    K > 0,
    K1 is K-1,
    coefficient(N,K,Zs),
    writeln(Zs),
    lineT(N,K1,[Zs|L]).

Result (condensed) : [debug] 124 ?- line(7,R). 1 7 21 35 35 21 7 1

Expected result (without writeln): [1,7,21,35,35,21,7,1]

false
  • 10,264
  • 13
  • 101
  • 209
Steve23
  • 113
  • 5

2 Answers2

2

Very easy: When describing a list, always consider using notation. For example:

line(N, Ls):-
    phrase(line_(N, N), Ls).

line_(_, 0) --> [1].
line_(N, K) --> [C],
    { K > 0,
      K1 is K-1,
      coefficient(N, K, C) },
    line_(N, K1).

Sample query:

?- line(3, Ls).
Ls = [1, 3, 3, 1] ;
false.

Personally, I no longer have the stomach for low-level integer arithmetic in Prolog, so I in fact recommend to use constraints for all integer arithmetic in Prolog programs:

:- use_module(library(clpfd)).

line(N,Ls):-
    phrase(line_(N, N), Ls).

line_(_, 0) --> [1].
line_(N, K) --> [C],
    { K #> 0,
      K1 #= K-1,
      coefficient(N, K, C) },
    line_(N, K1).

If you use CLP(FD) constraints consistently throughout your programs, you often obtain much more general relations that can be used in all directions.

You can also do this without DCGs of course, but then you need more arguments and more variables, which makes the code a bit harder to understand.

mat
  • 40,498
  • 3
  • 51
  • 78
0

should be enough to drop the writeln and fix the list construction.

lineT(_,0,[1]).
lineT(N,K,[Z|L]):-
    K > 0,
    K1 is K-1,
    coefficient(N,K,Z),
    lineT(N,K1,L).
CapelliC
  • 59,646
  • 5
  • 47
  • 90