2

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.
1
  • I'd suggest to use dcgs for this purpose. Commented Nov 12, 2013 at 17:12

2 Answers 2

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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).

2 Comments

there is printing the list:)
why don't you use findall ? :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.