I am asking for help in basic Prolog, a language whose paradigms are difficult for me to grasp. I am very familiar with other languages (C++, Lisp, Java, Assembly, etc.) but am a complete novice with Prolog.
What needs to be solved – in basic English: given 2 parameters, find a corresponding number in a 2D Array.
The problem is a brainlessly easy puzzle on the web which asks you to pick a number, choose that number’s color and then pick the house that contains your given number. The puzzle is set up such that there is only one number for each corresponding color/house combination.
What is currently in place:
function guess(Color, Houses) :-
<--Need what goes here -->
green(1, 15, 23, 24).
pink(2, 6, 10, 18).
etc...
houseA(2, 4, 7, 14).
etc...
The code must match the colors and houses to pick out the correct number. So for example, given "?- guess(pink, houseA)" should return "Your number is 2."
I have been writing down ideas on how to implement this in prolog and none of them get me any further. I do not know how I would implement if/else statements to check which color I should search, or how to check which numbers would correspond between house and color, or even how to “return” values!
It seems to me that I am missing a key point or…way of thinking about the language.
Any help would be appreciated. Thank you!
To return a value, you need another parameter in your predicate (not function btw). This parameter will be a free variable and you will bind it to the result.
In prolog specifications, such parameters are noted -Parameter while already bound parameters are noted +Parameter and parameters that can be both bound and free are noted ?Parameter. So here for you you could have a comment such as :
Then, predicates such as pink, houseA and so on are not that great to find numbers from. You can turn them into more adapted predicates by having numbers stored in a list :
When we got that list, we can write :
If you call guess(pink, houseA), that will call your predicate pink with argument Pool1, prolog will try to match Pool1 and [2, 6, 10, 18] so Pool1 is going to be bound to this list precisely.
Same with houseA and Pool2.
Now we tell prolog that we want our Result to be a member of Pool1
And a member of Pool2.
Finally we display the message.
Prolog will display result as R = x; false below that, if you don’t want the ; false part, you can add a “cut” :
=>
The !/0 predicate (cut) tells prolog not to backtrack to try to find other solutions. There it would have backtracked on member explaining why prolog returned a choice with only one result and false.
Hope it helps. If you got problems to understand some parts please say so and I’ll give infos.