2

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?

repeat
  • 18,496
  • 4
  • 54
  • 166
Jatin Khurana
  • 1,155
  • 8
  • 15
  • 2
    I found the mistake length function take two argument...... sorry for this silly mistake I am posting here........and one more error is I have taken variable name len in small letter... after correcting these two thing this is working fine.... – Jatin Khurana Sep 24 '14 at 20:55
  • 1
    Nevertheless, the error message that `[]` is expected, is pretty misleading. – false Sep 25 '14 at 13:07
  • yes .... that's why I was not able to find the error ... so posted here.... – Jatin Khurana Sep 25 '14 at 17:48

1 Answers1

2

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
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166