Tomas Ferreira
Tomas Ferreira

Reputation: 13

Print Matrix with a specific format in Prolog

Good night everyone!

I'm once again asking for help on behalf of a small project for my Logic Programming classes, with the theme being based around operations on matrices.

This time (and I hope it's the last since I'm really tired of this 'mini'-project), I want to print a matrix like this:

?- printMatrix([[1,2],[3,4],[5,6]]).
|: {{1,2},{3,4},{5,6}}

Well, as my tries on making the program output the matrix like that were garbage, I outputted the matrix on this format:

printMatrix([]).
printMatrix([M|Mt]) :- printMatrixln(M), nl, printMatrix(Mt).
printMatrixln([]).
printMatrixln([L|Lt]) :- write(L), write(' '), printMatrixln(Lt).


?- printMatrix([[1,2],[3,4],[5,6]]).
|: 1 2 
   3 4 
   5 6 
   true.

What I want to learn now is what I need to change on my code to output the matrix following the desired terminology (and not outputting like 4 curly brackets on a row like I was doing before).

Upvotes: 0

Views: 85

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 28993

What I want to learn now is what I need to change on my code

I don't know how to answer that, starting from your code. Starting from scratch I would do this:

To print the matrix:

  • print open brace {
  • print matrix content
  • print closing brace }

and for the content:

  • print first row open brace {
  • print first row content
  • print first row closing brace }
  • print comma between rows , unless at the end
  • print remaining rows

and for a row:

  • print first element
  • print comma between elements , unless at the end
  • print remaining elements

which I settled on while writing this code[1]:

printMatrixElems([]).
printMatrixElems([E|Es]) :-
    write(E),
    (Es = [] -> true    % write no comma after the last element.
     ; write(',')),     % write comma otherwise.
    printMatrixElems(Es).

printMatrixRows([]).
printMatrixRows([H|T]) :-
    write('{'),
    printMatrixElems(H),
    write('}'),
    (T = [] -> true
     ; write(',')),
    printMatrixRows(T).

printMatrix(Mx) :-
    write('{'),
    printMatrixRows(Mx),
    write('}').

and there is some repetition in the code for rows / elements, it's possible to merge into fewer but more complex predicates:

printMatrix_([], _, _).
printMatrix_([X|Xs], Before, After) :-
    write(Before),
    (X = [_|_] ->   
        printMatrix_(X, '', '')
    ;   write(X)),
    write(After),
    (Xs = [] -> true ; write(',')),
    printMatrix_(Xs, Before, After).

printMatrix(Mx) :-
    write('{'),
    printMatrix_(Mx, '{', '}'),
    write('}').

There may be something in format/2 which would help.

[1] I didn't write the steps first, then write the code. I thought of it, started writing the code, then when my code didn't work, thought again and changed the code, until with the help of the code I understood the problem enough to solve it.

Upvotes: 0

Related Questions