RosettaCodeData/Task/Ordered-words/Prolog/ordered-words.pro

45 lines
1.3 KiB
Prolog
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
:- use_module(library( http/http_open )).
ordered_words :-
% we read the URL of the words
2026-02-01 16:33:20 -08:00
http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', In, []),
read_file(In, [], Out),
close(In),
2023-07-01 11:58:00 -04:00
% we get a list of pairs key-value where key = Length and value = <list-of-its-codes>
% this list must be sorted
2026-02-01 16:33:20 -08:00
msort(Out, MOut),
2023-07-01 11:58:00 -04:00
2026-02-01 16:33:20 -08:00
group_pairs_by_key(MOut, POut),
2023-07-01 11:58:00 -04:00
% we sorted this list in decreasing order of the length of values
2026-02-01 16:33:20 -08:00
predsort(my_compare, POut, [_N-V | _OutSort]),
maplist(mwritef, V).
2023-07-01 11:58:00 -04:00
mwritef(V) :-
2026-02-01 16:33:20 -08:00
writef('%s\n', [V]).
2023-07-01 11:58:00 -04:00
read_file(In, L, L1) :-
2026-02-01 16:33:20 -08:00
read_line_to_codes(In, W),
( W == end_of_file ->
2023-07-01 11:58:00 -04:00
% the file is read
2026-02-01 16:33:20 -08:00
L1 = L
;
2023-07-01 11:58:00 -04:00
% we sort the list of codes of the line
2026-02-01 16:33:20 -08:00
% and keep only the "goods word"
( msort(W, W) ->
length(W, N), L2 = [N-W | L], (len = 6 -> writef('%s\n', [W]); true)
;
L2 = L
),
2023-07-01 11:58:00 -04:00
% and we have the pair Key-Value in the result list
2026-02-01 16:33:20 -08:00
read_file(In, L2, L1)).
2023-07-01 11:58:00 -04:00
% predicate for sorting list of pairs Key-Values
% if the lentgh of values is the same
% we sort the keys in alhabetic order
my_compare(R, K1-_V1, K2-_V2) :-
2026-02-01 16:33:20 -08:00
( K1 < K2 -> R = >; K1 > K2 -> R = <; =).