Get one of many possible solutions in Prolog
Asked Answered
R

1

6

I'm trying to learn Prolog. I looked at this script:

:- use_module(library(clpfd)).
puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]) :-
   Vars = [S,E,N,D,M,O,R,Y],
   Vars ins 0..9,
   all_different(Vars),
   S*1000 + E*100 + N*10 + D + M*1000 + O*100 + R*10 + E #= M*10000 + O*1000 + N*100 + E*10 + Y,
   M #\= 0,
   S #\= 0.

Source: https://github.com/Anniepoo/prolog-examples/blob/master/sendmoremoney.pl

I run it like so and get some output:

$ swipl -q -s sendmoremoney.pl
?- puzzle(X).
X = ([9, _G2009, _G2012, _G2015]+[1, 0, _G2024, _G2009]=[1, 0, _G2012, _G2009, _G2042]),
_G2009 in 4..7,
all_different([9, _G2009, _G2012, _G2015, 1, 0, _G2024, _G2042]),
91*_G2009+_G2015+10*_G2024#=90*_G2012+_G2042,
_G2012 in 5..8,
_G2015 in 2..8,
_G2024 in 2..8,
_G2042 in 2..8.

It looks like that is giving me a range of possible values for each letter. But how can I get a single solution where each letter is assigned to one of the possible values? Seems like a very basic question, but I can't figure it out.

Rom answered 8/8, 2016 at 3:22 Comment(0)
R
4

Ok, looks like this wasn't so much a Prolog question as a clpfd question.

?- puzzle(As + Bs = Cs), label(As).
As = [9, 5, 6, 7],
Bs = [1, 0, 8, 5],
Cs = [1, 0, 6, 5, 2] ;
false.

Found my answer here: http://www.swi-prolog.org/man/clpfd.html

Rom answered 8/8, 2016 at 3:35 Comment(3)
s(X) for figuring it out, and for linking to the documentation! Many examples you find on the internet, including the one you linked to, are ripped off from the CLP(FD) documentation, but lack the proper context and use bad practices. Read the documentation first, then use the official information to find the flaws in other texts!Snow
@mat, you seem to be conflating CLP(FD) (a theoretical concept and subject of the clpfd tag) and implementations called clpfd (of which, confusingly, there are two quite different ones, SICStus Prolog's and SWI/?-Prolog's). The send-more-money example is from the 1989 book Constraint Satisfaction in Logic Programming by Pascal Van Hentenryck, and has appeared with minor syntactic adjustments in every text on CLP(FD) since. If it's ripped off from anywhere, then from there...Reprography
Yes the example is also used elsewhere. A link to other and better documentation would have been just as good. In this concrete case, please see the concrete syntax that is used to see where the example was copied from.Snow

© 2022 - 2024 — McMap. All rights reserved.