% Predicate to start the measurement process
weight :- measure(0, 0, 0, 0).
% Predicate to handle the input and measurement process
measure(S_sum, S_num, O_sum, O_num) :-
write('Enter weight (0 to stop): '),
read(X),
( X =:= 0 ->
( S_num =:= 0 -> AvgS = 0 ; AvgS is S_sum / S_num ),
( O_num =:= 0 -> AvgO = 0 ; AvgO is O_sum / O_num ),
nl,
write('The average strawberry weight: '), write(AvgS), nl,
write('The average orange weight: '), write(AvgO), nl
;
accumulate(X, S_sum, S_num, O_sum, O_num)
).
% Predicate to accumulate weights and numbers of strawberries and oranges
accumulate(X, S_sum, S_num, O_sum, O_num) :-
( X >= 15, X =< 25 ->
add(X, S_sum, S_num, NS_sum, NS_num),
measure(NS_sum, NS_num, O_sum, O_num)
; X >= 125, X =< 200 ->
add(X, O_sum, O_num, NO_sum, NO_num),
measure(S_sum, S_num, NO_sum, NO_num)
;
write('Invalid weight. Please enter a valid weight for strawberry (15-25g) or orange (125-200g).'), nl,
measure(S_sum, S_num, O_sum, O_num)
).
% Predicate to update the weights and counts
add(X, Sum, Num, NSum, NNum) :-
NSum is Sum + X,
NNum is Num + 1.
Write, Run & Share Prolog code online using OneCompiler’s Prolog online compiler for free. It’s a simple and intuitive platform to experiment with logic programming in Prolog. OneCompiler supports standard Prolog syntax, great for learning, prototyping, and practicing logic-based problems.
Prolog (Programming in Logic) is a logic programming language associated with artificial intelligence and computational linguistics. It works through facts, rules, and queries, using a form of symbolic reasoning known as backward chaining. Prolog is declarative, meaning you describe what you want instead of how to compute it.
The following is a simple Prolog program that prints a greeting:
:- initialization(main).
main :-
write('Hello, World!').
Facts represent basic assertions about the world.
likes(alice, pizza).
likes(bob, pasta).
Rules define logical relationships using facts.
friends(X, Y) :- likes(X, Z), likes(Y, Z).
Queries are used to find information based on facts and rules.
?- likes(alice, What).
| Operator | Description |
|---|---|
:- | Rule definition |
, | Logical AND |
; | Logical OR |
= | Unification |
member(X, [X|_]).
member(X, [_|T]) :- member(X, T).
Prolog heavily relies on recursion.
factorial(0, 1).
factorial(N, F) :-
N > 0,
N1 is N - 1,
factorial(N1, F1),
F is N * F1.
This guide provides a quick reference to Prolog programming syntax and features. Start writing Prolog code using OneCompiler’s Prolog online compiler today!