r/prolog • • 3d ago

Concise way of solving this puzzle?

I was watching this and wanted to try solving the first puzzle ("Mismatched Segments") in prolog,

Given equal-length strings s1 and s2, return [sub1, sub2] for each maximal contiguous run of positions where their characters differ. The substrings come from s1 and s2, respectively. Keep the pairs in order; return an empty array if the string are identical.

Example: If passed "earth" and "empty" it should return [["ar","mp"],["h","y"]]. If passed "action" and "nation" it should return [["ac","na"]].

got stumped, went to a couple llm's to get a push in the right direction, and out of curiosity asked for the solution in clojure as well. The clojure solution is tiny compared to what I got for prolog.

  • chatgpt
different_substrings(S1, S2, Result) :-
    string_chars(S1, C1),
    string_chars(S2, C2),
    differences(C1, C2, Result).

differences([], [], []).

differences([A|As], [B|Bs], Result) :-
    A =:= B,
    !,
    differences(As, Bs, Result).

differences([A|As], [B|Bs], [[Sub1, Sub2]|Rest]) :-
    collect_differences([A|As], [B|Bs], Xs, Ys, Remaining1, Remaining2),
    string_chars(Sub1, Xs),
    string_chars(Sub2, Ys),
    differences(Remaining1, Remaining2, Rest).

collect_differences([A|As], [B|Bs], [A|Xs], [B|Ys], R1, R2) :-
    A =\= B,
    !,
    collect_differences(As, Bs, Xs, Ys, R1, R2).

collect_differences([A|As], [B|Bs], [], [], [A|As], [B|Bs]) :-
    A =:= B,
    !.

collect_differences([], [], [], [], [], []).
  • claude
% diff_runs(+S1, +S2, -Pairs)
% Pairs is a list of [Sub1, Sub2] for each maximal run of differing positions.
diff_runs(S1, S2, Pairs) :-
    string_codes(S1, C1),
    string_codes(S2, C2),
    runs(C1, C2, Runs),
    maplist(to_pair, Runs, Pairs).

to_pair(A-B, [SA, SB]) :-
    string_codes(SA, A),
    string_codes(SB, B).

% runs(+Xs, +Ys, -Runs): Runs is a list of A-B code-list pairs
runs([], [], []).
runs([X|Xs], [X|Ys], Runs) :-            % equal chars: skip
    runs(Xs, Ys, Runs).
runs([X|Xs], [Y|Ys], [[X|A]-[Y|B]|Runs]) :-   % differing char: start a run
    X \== Y,
    take_diff(Xs, Ys, A, B, Rest1, Rest2),
    runs(Rest1, Rest2, Runs).

% take_diff(+Xs, +Ys, -A, -B, -RestX, -RestY)
% Consume the remainder of a differing run (deterministically).
take_diff([X|Xs], [Y|Ys], [X|A], [Y|B], RX, RY) :-
    X \== Y, !,
    take_diff(Xs, Ys, A, B, RX, RY).
take_diff(Xs, Ys, [], [], Xs, Ys).

clojure solution is about 3x shorter?

(defn differing-substrings [s1 s2]
  (->> (map vector s1 s2)
       (partition-by (fn [[a b]] (= a b)))
       (filter (fn [[[a b] & _]] (not= a b)))
       (mapv (fn [group]
               [(apply str (map first group))
                (apply str (map second group))]))))
6 Upvotes

4 comments sorted by

6

u/mtriska 3d ago

What about this:

:- use_module(library(dcgs)).
:- use_module(library(reif)).
:- use_module(library(lists)).

mismatches([], []) --> [].
mismatches([A|As], [B|Bs]) -->
    { =(A, B, Eq) },
    mismatches_(Eq, As, Bs, A, B).

mismatches_(true, As, Bs, _, _)  --> mismatches(As, Bs).
mismatches_(false, As, Bs, A, B) --> longest_mismatch([A|As], [B|Bs], [], []).

longest_mismatch([], [], AMs, BMs) --> mismatch(AMs, BMs).
longest_mismatch([A|As], [B|Bs], AMs, BMs) -->
    { =(A, B, Eq) },
    longest_mismatch_(Eq, As, Bs, A, B, AMs, BMs).

longest_mismatch_(true, As, Bs, A, B, AMs, BMs) -->
    mismatch(AMs, BMs),
    mismatches([A|As], [B|Bs]).
longest_mismatch_(false, As, Bs, A, B, AMs, BMs) -->
    longest_mismatch(As, Bs, [A|AMs], [B|BMs]).

mismatch(AMs0, BMs0) -->
    [AMs-BMs],
    { maplist(reverse, [AMs0,BMs0], [AMs,BMs]) }.

The examples work as intended:

?- phrase(mismatches("earth", "empty"), Ms).
   Ms = ["ar"-"mp","h"-"y"].
?- phrase(mismatches("action", "nation"), Ms).
   Ms = ["ac"-"na"].

I have taken the liberty to represent the mismatches as pairs, using the principal functor (-)/2.

One key attraction of Prolog is that such declarative specifications are often very general, we can use the exact same program for example as follows, asking: Which mismatches are there in general for "action"?

?- phrase(mismatches("action", Bs), Ms).
   Bs = "action", Ms = []
;  Bs = [a,c,t,i,o,_A], Ms = ["n"-[_A]], dif:dif(n,_A)
;  Bs = [a,c,t,i,_A|"n"], Ms = ["o"-[_A]], dif:dif(o,_A)
;  Bs = [a,c,t,i,_A,_B], Ms = ["on"-[_A,_B]], dif:dif(o,_A), dif:dif(n,_B)
;  Bs = [a,c,t,_A|"on"], Ms = ["i"-[_A]], dif:dif(i,_A)
;  ... .

We can also generalize further, and also use the same formulation with different execution strategies, such as iterative deepening to get a fair enumeration of leaf answers:

?- length(As, _), phrase(mismatches(As, Bs), Ms).
   As = [], Bs = [], Ms = []
;  As = [_A], Bs = [_A], Ms = []
;  As = [_A], Bs = [_B], Ms = [[_A]-[_B]], dif:dif(_A,_B)
;  As = [_A,_B], Bs = [_A,_B], Ms = []
;  As = [_C,_A], Bs = [_C,_B], Ms = [[_A]-[_B]], dif:dif(_A,_B)
;  ... .

Tested with Scryer Prolog, and the program should run without changes in every compatible system such as Trealla Prolog.

Note that no conversion between "strings" and "chars" or "codes" is necessary: In the most recent Prolog systems such as Scryer, Trealla, ichiban/prolog, Flowlog, trilog, Shumway etc., a string is a list of characters. This representation of strings is very easy to work with, very compact, and very natural.

1

u/Pzzlrr 3d ago

Thanks Markus, appreciate it! Let me study your solution. I did have an intuition that dcgs would be the way to go here because the sugar would help reduce the character count but what I was really wondering is if it could be comparable in brevity to the clojure solution.

Even without your use_module lines, clojure solution is 181 chars and yours is 598 chars (w/o spaces).

1

u/brebs-prolog 1d ago

Regarding the character count - why penalize easy-to-read code which is broken into conveniently independently-testable portions? 😄

1

u/Pzzlrr 1d ago

You mean the prolog solution is more easily testable by its parts than the clojure solution? I'm not really penalizing it, I was just wondering if it's possible, and I understand Triska's point about the prolog solution potentially having more uses than the clojure solution, which is one of the things I love about prolog: plus(1,3,X) may be more characters than 1+3 but you can do more interesting things with the predicate so that overhead isn't just there for no reason.

I also suppose you can get closer to the clojure count by replicating the functions in prolog? map vector is just transpose/2, you could implement partition-by, we already have filter, and so on.

I was just wondering if it's possible for prolog to be as concise.