Search code examples
prolog

How can I create in prolog a list of lists of triplets with the prev and the next elements of each element?


I´ve been trying to take de elements from a list and make a list of lists of three elements, for examnple:
from the list [1,2,3,4] the result would be [[null,1,2],[1,2,3],[2,3,4],[3,4,null]].

But i donn´t get to obtain the head or the end of the list, I can just get [[1,2,3],[2,3,4],[3,4,null]] or [[null,1,2],[1,2,3],[2,3,4]]. This is the funcion:

take_with_neighbors([X|Xs], Result) :-
    take_with_neighbors(Xs, X, Result).
take_with_neighbors([X|Xs], Prev, [[Prev,X,Next]|Result]) :-
    take_with_neighbors(Xs, X, Result),
    ( Xs = [Next|_] ; Next = null ).
take_with_neighbors([], _, []).

This returns: [[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,null]], with no [null,1,2]

And this other function:

get_adjacent_elements_helper([Primero|T], Result) :-
    get_adjacent_elements_helper(null, Primero, T, Result).

get_adjacent_elements_helper(_, Primero, [], [Primero, null]) :- !.
get_adjacent_elements_helper(Prev, Primero, [Next|T], Result) :-
    Result = [[Prev, Primero, Next] | Rest],
    get_adjacent_elements_helper(Primero, Next, T, Rest).

This returns [[null,1,2],[1,2,3],[2,3,4],[3,4,5],[4,5,6],6,null], almost


Solution

  • A possible solution is:

    triplets(List, Triplets) :-
        triplets_helper([null|List], Triplets).          % insert null at beginning   
    
    triplets_helper([X1,X2], [[X1,X2,null]]) :- !.       % insert null at the end
    triplets_helper([X1,X2,X3|Xs], [[X1,X2,X3]|Ys]) :-
        triplets_helper([X2,X3|Xs], Ys).
    

    Examples:

    ?- triplets([1,2,3,4], T).
    T = [[null, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, null]].
    
    ?- triplets([1,2,3], T).
    T = [[null, 1, 2], [1, 2, 3], [2, 3, null]].
    
    ?- triplets([1,2], T).
    T = [[null, 1, 2], [1, 2, null]].
    
    ?- triplets([1], T).
    T = [[null, 1, null]].
    
    ?- triplets([], T).
    false.
    
    ?- triplets(L, [[null, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, null]]).
    L = [1, 2, 3, 4].