1

There was a question to turn a list (of any length) to a matrix here (see link at the bottom), but I'd like to do the opposite, turn a matrix into a list, recursively.

Matrix = [[a,b,c],[d,e,f]]

define predicate :

matrixToList(MyMatrix,NewList)

where NewList = [a,b,c,d,e,f].

Can anyone please help?
Thank you.

Turn a list into a matrix

Community
  • 1
  • 1
Gia Sadhwani
  • 73
  • 1
  • 4
  • 2
    Can you just [`flatten/2`](http://www.swi-prolog.org/pldoc/doc_for?object=flatten/2) the list? – Shon Apr 02 '14 at 00:41
  • 2
    I'm wondering, are all of the Prolog classes these days teaching and proliferating the use of camel case for Prolog functor names? As @aBathologist suggests, `matrix_to_list(MyMatrix, NewList) :- flatten(MyMatrix, NewList).` would be the cleanest implementation. – lurker Apr 02 '14 at 02:06
  • @mbratch I don't think it is on purpose, most likely a habit from Java programming. If you follow the coding conventions nicely described here: http://arxiv.org/abs/0911.2899 it would then be also `My_Matrix` or even `My_matrix`. –  Apr 02 '14 at 07:38
  • @Boris you may be right. The most popular languages encourage it and it spills over. I find myself using it for variable names in Prolog, but not with functors. – lurker Apr 02 '14 at 09:56
  • 1
    @aBathologist: Using `flatten/2` is definitely a bad idea: A matrix of matrices of integers would thus be flattened to a list of integers and not a list of matrices of integers. – false Apr 03 '14 at 17:41
  • 1
    See [this answer](http://stackoverflow.com/a/9787502/772868) – false Apr 03 '14 at 17:44
  • @false that makes sense. I suppose my view was too limited to the specific case. – Shon Apr 03 '14 at 21:36

1 Answers1

0

This is my code for the same problem, but yes, you can also use flatten

getAllElements([],[]).
getAllElements([H|T], ElementsList) :- getAllElements(T, NewElementsList),
                                       append(NewElementsList, H, ElementsList).
Ana-Maria
  • 41
  • 5