% ES 95 Midterm Exam Solutions % Solution to Problem 1 member(E,[E|_]). member(E,[_|T]):-member(E,T). pickFoods(Avail,Cal,Poss):- pickFoods1(Avail,Cal,[],0,Poss). % pickFoods1(Avail,Cal,NotChosen,CalSoFar,Chosen) does the actual work. % Avail is the list of available foods. pickFoods1 will examine one % of these and do a recursive call on the rest. % Cal is the energy limit for the meal. It does not change with recursion. % NotChosen is a list of foods which were considered but not chosen for % the meal. % CalSoFar is the energy in the foods chosen so far. These foods % are held in the instances "above". % Chosen is the list of foods chosen by pickFoods1. % Add a food (Food) to the Chosen list. % pickFoods1([Food|More],Cal,NotChosen,SoFar,[Food|ChosenBelow]):- food(Food,FC), Next is SoFar+FC, Next =< Cal, pickFoods1(More,Cal,NotChosen,Next,ChosenBelow). % Do not add food to Chosen list. Instead it is added to the NotChosen % list. % pickFoods1([FoodOmitted|More],Cal,NotChosen,SoFar,ChosenBelow):- pickFoods1(More,Cal,[FoodOmitted|NotChosen],SoFar,ChosenBelow). % No more foods in Avail list. If any of the NotChosen foods could % be added to the list then fail. Otherwise succeed. (Failure would % result in backtracking which in turn would result in the food % being added to the list.) % pickFoods1([],Cal,NotChosen,SoFar,[]):- Rem is Cal-SoFar, not((food(F,C),member(F,NotChosen),C=