Search code examples
listprologdecoderun-length-encoding

run length decoding of a list in prolog?


I'm trying to decode a given list for example mydecode([(a,1), (b,2), (c,3), (d,2)],X) should give X = ['a','b','b','c','c','c','d','d']. What is the error in this code?

mydecode([],[]).
mydecode([X|Ys],[X|Zs]) :- \+ is_list(X), mydecode(Ys,Zs).
mydecode([[1,X]|Ys],[X|Zs]) :- mydecode(Ys,Zs).
mydecode([[N,X]|Ys],[X|Zs]) :- N > 1, N1 is N - 1, mydecode([[N1,X]|Ys],Zs).

Solution

    • you are asked to handle a list of 'tuples' of 2 elements, not a list of lists of 2 elements
    • then, the test in the second clause will always fail
    • the tuples elements are key and value, but you're 'accessing' them in inverse order.

    So, remove the second clause - it's irrelevant, since pattern matching will discard ill formed lists. Change the [1,X] to (X,1) and similarly other references to tuples, and test your code with the query assigned.