Francisco Cunha
Francisco Cunha

Reputation: 85

Split list of strings into list of lists in prolog

I am beggining to learn Prolog and I would like to know how to implements a function that turns a list of strings into an ordered list of lists of characters. For example:

?- f([sheep,dog,cat],Z).

should return

Z=[[c,a,t], [d,o,g], [s,h,e,e,p]].

I know i should use the predicates sort(L1,L2) and atom_chars(A,B) respectively. But how exactly do I write the code? There are very few Prolog tutorials online so I really don't know how to put it... Thanks in advance!

Upvotes: 0

Views: 94

Answers (1)

David Tonhofer
David Tonhofer

Reputation: 15316

Inspired by false's oneliner, wrapped by unit testing framework:

:-begin_tests(split).

data([sheep,dog,cat]).

test(one) :- data(L),
             sort(L,L2),
             maplist(atom_chars,L2,Exploded),
             format("~q\n",[Exploded]),
             L2 = [[c,a,t], [d,o,g], [s,h,e,e,p]]. 


:-end_tests(split).

rt :- run_tests(split).
?- rt.
% PL-Unit: split [[s,h,e,e,p],[d,o,g],[c,a,t]]
. done
% test passed
true.

Upvotes: 1

Related Questions