Reputation: 33
I've been trying to use prolog recursion to get the following output. ?- triangle(5).
++++1
+++12
++123
+1234
12345
This is what I've done so far but it doesn't give me expected output.
triangle(X):-X>=1,nl, LS is X-1,plus(LS),triangle(LS),process(X),nl.
triangle(X):-X=<1.
process(X):- X>=1,NS is X+1,process(NS),write(X).
process(X):-X=<1.
plus(N):-N>=1, LS is N-1, write('+'),plus(LS).
plus(N):-N=<1.
Upvotes: 2
Views: 714
Reputation: 1712
Decided to try and solve it with findall so here is my solution :)
print_array([]):-nl.
print_array([H|T]) :- maplist(write,H),nl,print_array(T).
triangle(N) :- numlist(1,N,Nums),
findall('+',member(_,Nums),Pluses),
findall(R,(prefix(NumL,Nums),prefix(P,Pluses),not(NumL=[]),length(P,PL),length(NumL,NL),N is PL+NL,append(P,NumL,R)),Rez),
print_array(Rez).
Upvotes: 0
Reputation: 60004
You need to add a variable for each dimension you want to 'loop around'.
Then iterate each row, and in each row iterate on columns. Instead of adding new predicate' names, you can add variables to distinguish:
triangle(N) :-
triangle(1, N).
triangle(R, N) :-
triangle(1, R, N),
( R < N
-> R1 is R+1,
triangle(R1, N)
; true
).
triangle(C, R, N) :-
( C =< N-R
...
),
( C < N
...
; nl
).
In the row print rule, I leave some - tricky - code to find out for your practice :)
Upvotes: 1