4 ms·
:- use_module(library(clpfd)). rle([], []). rle([H],[[H, 1]]). rle([H | T], [[H, CountPlus1] | More]) :- Count #> 0, CountPlus1 #= Count+1,
by superdisk 3y ago
:- use_module(library(clpfd)).
rle([], []).
rle([H],[[H, 1]]).
rle([H | T], [[H, CountPlus1] | More]) :-
Count #> 0,
CountPlus1 #= Count+1,
rle(T, [[H, Count] | More]).
rle([H | T], [[H, 1], [Element, Count] | More]) :-
Count #> 0,
dif(Element, H),
rle(T, [[Element, Count] | More]).
Even though I'm the one who was making the execution model complaint, this implementation seems to work for me.
?- rle([1,1,1,2,3,1,1],X), rle(Y, X).
X = [[1, 3], [2, 1], [3, 1], [1, 2]],
Y = [1, 1, 1, 2, 3, 1, 1] ;
false.
- falsissime 3y agoThere is a minor impurity in this code: `N = 1+1, rle([a,a],[[a,N]]).` succeeds, yet `rle([a,a],[[a,N]]), N = 1+1` fails. Add `:- op(150, fx, #).` and use it like `#CountPlus1 #= #Count+1` etc.
- ghusbands 3y agoI was lumping clpfd under metaprogramming, since it acts like an extra runtime or dsl and you can't use the prolog debugger to make sense of it. I'll readily admit that prolog+clpfd is very powerful; any goalpost-moving on my part is unintentional. I found that using peano numbers got a bit further in plain prolog, but it still eventually infloops in at least one of the directions.