Search code examples
prologdcg

run length encoding using DCGs


problem from: https://web.archive.org/web/20200718175929/http://www.pathwayslms.com/swipltuts/dcg/

Use a dcg to convert a sparse sequence like

[0,0,0,0,0,0,7,4,3,0,0,0,0,0,0,0,8,9,14,0,0,0,0....]

to

[zero(6), 7,4,3, zero(7), 8,9,14, ...]

i feel like i understand the material on this page up to here but don't really know how to start this one. any pointers would be appreciated


Solution

  • Try doing something like this:

    code([X|Xs]) --> item(X), code(Xs).
    code([])     --> [].
    
    item(X) --> [0], zeros(1, X).
    item(X) --> [X], { X \= 0 }.
    
    zeros(M, N)       --> [0], { M1 is M + 1 }, zeros(M1, N).
    zeros(N, zero(N)) --> \+ [0].
    

    Example:

    ?- phrase(code(C), [0,0,0,0,0,0,7,4,3,0,0,0,0,0,0,0,8,9,14,0,0,0,0]).
    C = [zero(6), 7, 4, 3, zero(7), 8, 9, 14, zero(4)] ;
    false.