0

I am writing a basic program in prolog but I don't get it to work. This is the code:

My prolog code.

borders(sweden,finland,586).
borders(norway,sweden,1619).

allborders(X,Y,L) :- borders(X,Y,L).
allborders(X,Y,L) :- borders(Y,X,L).
addborders(C,Lsum,Set) :- length(Set,0), write(C), write(' - '), write(Lsum), C == Lsum.
addborders(C,Lsum,[H|T]) :- Lsum2 is Lsum + H, addborders(C,Lsum2,T).
helpsetofpredicate(Country,L) :- allborders(Country,_,L).
circumference(C,Country) :- setof(L,helpsetofpredicate(Country,L),Set), addborders(C,0,Set).

(Obs: the borders are just a small sample for a gigantic file but are enough to describe the problem)

So what this program is supposed to do is to sum all the borders to a country and check if the given circumference (C) is the total of a countries circumference (Country). If I were to type

circumference(2205,sweden).

the program gives true, which is expected. But if I type

circumference(C,sweden).

the program gives false. I have put some writes within the code to see which values C and Lsum has and the output is _G962 - 2205. Why doesn't prolog assign a correct value to C instead of giving it a random value?

false
  • 10,264
  • 13
  • 101
  • 209
Donkey King
  • 87
  • 1
  • 8

1 Answers1

1

My Prolog is a bit rusty, but if you change C == Lsum to C = Lsum (in your first addborders predicate) it works.

That is because in your predicate, it evaluates C == Lsum and that is not true. But with a single '=' Prolog tries to match it and that is possible if C equals 2205.

See also https://stackoverflow.com/a/8220315/5609233 for difference '=' and '=='.

J. Kamans
  • 575
  • 5
  • 17
  • Thank you very much for your time. I am having a hard time getting a grip of that concept. I did what you suggested before, but to me it feels strange to just assign the correct value to the variable haha do you understand what I mean? – Donkey King Nov 28 '18 at 00:24
  • Totally. I learned Prolog during a minor, it took quite a while before I understood it with a regular programming background (Java, JS, Python etc) – J. Kamans Nov 28 '18 at 00:35
  • 1
    @DonkeyKing, `=/2` is the unification operator. `==/2` succeeds only if the arguments are identical. So `X == a` fails unless `X` is already bound to `a`. But `X = a` unifies the variable with the atom, `a` (binds it) assuming it's not already bound. – lurker Nov 28 '18 at 01:21