Jatin Khurana
Jatin Khurana

Reputation: 1175

Getting error while calling length on list in Prolog

I am new to Prolog and solving the 99 Prolog problems from the following link:

http://www.ic.unicamp.br/~meidanis/courses/mc336/2009s2/prolog/problemas/

I have written a solution of Problem #10. Below is my solution:

encode(L,Ans) :-
   pack(L,Res),
   encode_list(Res,Ans).

encode_list([],[]).
encode_list([[X|Xs]|Zs],[[len,X]|Ans]) :- 
   len is length([X|Xs]),
   encode_list(Zs,Ans).

pack([],[]).
pack([X|Xs],[Y|Ys]) :-
   transfer(X,Xs,Zs,Y),
   pack(Zs,Ys).

transfer(X,[],[],[X]).
transfer(X,[Y|Ys],[Y|Zs],[X]) :-
   X =\= Y,
   transfer(X,Ys,Zs,[X]).
transfer(X,[X|Xs],Ys,[X|Zs]) :- 
   transfer(X,Xs,Ys,Zs).

What I am doing is first packing the same number like suppose encode([1,1,1,1,1,2,2,2,3,3],X) is called so first I pack the same number like [[1,1,1,1,1],[2,2,2],[3,3]] and then find its length and then group them according to the requirement.

It is packing the similar number correctly but when I am calling encode_list and then calling the length function, it's giving me the following error:

ERROR: is/2: Type error: `[]' expected, found `[1,1,1]' ("x" must hold one character)

Anyone please help me! Why it is giving this error?

Upvotes: 2

Views: 194

Answers (1)

repeat
repeat

Reputation: 18726

Based on splitlistIfAdj/3, dif/3, maplist/3, Prolog lambdas, and length/2, we write:

:- use_module(library(lambda)).

encode(Ls,Xs) :-
   splitlistIfAdj(dif,Ls,Rs),
   maplist(\[E|Es]^[N,E]^length([E|Es],N),Rs,Xs).

Sample query:

?- encode([a,a,a,a,b,c,c,a,a,d,e,e,e,e],Xs).
Xs = [[4,a],[1,b],[2,c],[2,a],[1,d],[4,e]].    % succeeds deterministically

Upvotes: 2

Related Questions