Home > Back-end >  Extract a column from a matrix (list of lists) in prolog
Extract a column from a matrix (list of lists) in prolog

Time:11-15

For an input like extract_column([[1,2], [3, 4], [5,6]], 0, X)., I'd like to see the result as [1,3,5]. I'm not sure if my base case is correct or how to proceed with the recursive logic.

The point is to get the Ith element of the header (list), append it to the result list R and recursively apply that logic to all of the lists inside the big list.

extract_column([], [R1]).
extract_column([H|T], I, [R]) :-
   extract_column([T], I, [R1]),
   nth0(I, [H], num1),
   append([R], num1, R1).

CodePudding user response:

Indeed, the base case is not correct and furthermore there is no need to use append/3.

  • The base case should define a predicate of arity 3 (i.e., with arguments Matrix, Index, Column).
  • To add an element Y to the beginning of a list Ys, just write [Y|Ys].
  • For more efficiency, it's better to use tail recursion (moving the recursive call to the end of the clause).

Thus, a possible solution is:

extract_column([], _, []).
extract_column([X|Xs], I, [Y|Ys]) :-
    nth0(I, X, Y),
    extract_column(Xs, I, Ys).

Examples:

?- extract_column( [[1,2], [3, 4], [5,6]], 0, Col).
Col = [1, 3, 5].

?- extract_column( [[1,2], [3, 4], [5,6]], I, Col).
I = 0,
Col = [1, 3, 5] ;
I = 1,
Col= [2, 4, 6].
  • Related