Pack consecutive duplicates of list elements into sublists

list, prolog

Solution

Your forth clause tries to append `[H|HS]` to the result, which is incorrect, because `[H|HS]` is the tail of the original list. You can make it a lot simpler -

pack([H, H|HS], [[H|TFR]|TR]):-
    pack([H|HS], [TFR|TR]).

Essentially, it says that when the first two entries are the same in the input, the first entry (i.e. `H`) needs to be pre-pended to the first entry of the output list produced by recursive invocation of the `pack` rule.

Note that the third clause can be simplified as well by replacing the `Liste` parameter which you "crack" right away with the "cracked" version "inlined" into the header of the clause, and doing the same to the output variable `Ergebnis1`. The final version should look like this:

pack([H, T|TS], [[H]|TR]):-
    H \= T,
    pack([T|TS], TR).

Here is a demo on ideone.

Problem

I need some help. I searched through the database and I found one question already asked about this example, but the answers didn't really help me, so I thought to post my own question. The task is to pack consecutive duplicates of list elements into sublists: ``` % ?- pack([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X). % X = [[a,a,a,a],[b],[c,c],[a,a],[d],[e,e,e,e]]. ``` Here is what I got: ``` pack([], []). pack([X], [[X]]). pack(Liste, Ergebnis):- Liste = [H, T|TS], H \= T, pack([T|TS], Ergebnis1), append([[H]], Ergebnis1, Ergebnis). pack([H, H|HS], Ergebnis):- pack([H|HS], Ergebnis1), append([H|HS], Ergebnis1, Ergebnis). ``` The first case works really well (case where H \= T). The second one doesn't, and I really don't know why. Could someone please help me and explain the problem according my solution? Thanks

Original source

Related problems