Reputation: 15062
I'm working on an expert system assignment in Prolog, and I'm trying to improve my code. The system shows the user questions, each one has an answer between a range (always, often, rarely, never). for each question, I want to add the value into the final sum. As you know, in Prolog the variables are not assignable, so I use this next trick:
anyDisorder(Res):-
Sum is 0,
checkSymptom('Do you feel lonely?', Sum, Sum1),
checkSymptom('Do you feel sad?', Sum1, Sum2),
checkSymptom('Do you wish to be somewhere else?', Sum2, Sum3),
Res is Sum3.
You can see that each time I assign a new variable in order to calculate the sum. It works, but I don't feel fine with it.
Does anyone have any suggestion in which I can use instead?
Upvotes: 2
Views: 109
Reputation: 476729
Prolog the variables are not assignable
You are correct. But the idea is not to "emulate" imperative programming. Actually the fact that variables are not assignable, should "force" you to think in a more logic programming way.
For instance you do not need a variable to keep track of the sum. You can simply store the outcome of the questions in variables X1
, X2
and X3
and sum them up later in your program.
So I propose to make checkSymptom/2
return only the value, and then write Res is X1 + X2 + X3
as last statment:
anyDisorder(Res):-
checkSymptom('Do you feel lonely?', X1),
checkSymptom('Do you feel sad?', X2),
checkSymptom('Do you wish to be somewhere else?', X3),
Res is X1+X2+X3.
And thus write it as:
checkSymptom(Query, Outcome) :-
%% ...
%% ask the question
%% set outcome to an integer
At first I found the fact that variables can not be assigned weird. But later I realized this helps prevent people from getting a lot of headaches. The above more declaratively and explicitly shows what you are doing.
Upvotes: 2