RabbitFarm
2025-04-12
The Weekly Challenge 316 (Prolog Solutions)
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1: Circular
You are given a list of words. Write a script to find out whether the last character of each word is the first character of the following word.
We can do this in a single predicate which recursively examines the list of words, which we’ll take as a list of character code lists.
-
circular([]).
circular([_]).
circular([H0, H1|T]):-
last(H0, C0),
nth(1, H1, C1),
C0 = C1,
circular([H1|T]).
◇
-
Fragment referenced in 2.
The rest of the code just wraps this predicate into a file.
Sample Run
$ gprolog --consult-file prolog/ch-1.p | ?- circular(["perl", "loves", "scala"]). true ? (1 ms) yes | ?- circular(["love", "the", "programming"]). no | ?- circular(["java", "awk", "kotlin", "node.js"]). true ? yes | ?-
Part 2: Subsequence
You are given two strings. Write a script to find out if one string is a subsequence of another.
This is going to be a quick one, seeing as GNU Prolog has a sublist/2 predicate which does exactly this! As in the previous part we’ll take the strings as lists of character codes.
Finally, let’s assemble our completed code into a single file.
Sample Run
$ gprolog --consult-file prolog/ch-2.p | ?- subsequence("uvw", "bcudvew"). true ? yes | ?- subsequence("aec", "abcde"). no | ?- subsequence("sip", "javascript"). true ? yes | ?-
References
posted at: 23:32 by: Adam Russell | path: /prolog | permanent link to this entry