Search code examples
prologswi-prolog

converting character list to list of strings with each one contains 3 characters in Prolog


I want to convert list of character to list of strings with each one contains 3 characters using Prolog.

For example, ['a','b','c','d','e','f'] will be converted to ["abc", "def"].

What I tried was

toTriplets([H1|[H2|[H3|T]]],[F|R]) :- string_concat(H1,H2,X) , string_concat(X,H3,F) , toTriplets(T,R).

However, this gives me false when I execute the command

?- toTriplets(['a','b','c','d','e','f'],X).
false.

What is the problem with my code? I really can't figure it out...


Solution

  • The problem is you're missing the base case of recursion. For instance

    toTriplets([],[]).
    

    Indeed there you have the chance to decide if accept only triples - as above - or accept also incomplete ones, like

    toTriplets([A,B],[AB]) :- string_concat(A,B,AB).
    toTriplets([A],[S]) :- atom_string(A,S).