:- module(shiritori, [shiritori_load_data/2, shiritori/4]). shiritori_load_data(Path,Data) :- open(Path,read,Stream,[encoding(utf8)]), construct_array(Stream,[],Data), close(Stream). construct_array(Stream,Buffer,Data) :- construct_word(Stream,[],Last,Word), (Word == [] -> Added = Buffer; Added = [Word|Buffer]), (Last == end_of_file -> reverse(Added,Data); construct_array(Stream,Added,Data)). construct_word(Stream,Buffer,Last,Word) :- get_char(Stream,Char), ((Char == end_of_file; Char == ','; Char == '\n') -> Last = Char, reverse(Buffer,Word); construct_word(Stream,[Char|Buffer],Last,Word)). shiritori(W0,W1) :- W1 = [H|_], last(W0,H). shiritori([],Data,Data,0). shiritori([W],Data,Rest,1) :- select(W,Data,Rest). shiritori([W0,W1|S],Data,Rest,N) :- N>1, N1 is N-1, select(W0,Data,R0), shiritori(W0,W1), shiritori([W1|S],R0,Rest,N1).