The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
You are given a stream of numbers, @N. Write a script to print the average of the stream at every point.
:-initialization(main). moving_average(N):- moving_average(0, N, 1). moving_average(Sum, N, I):- I \== N, Sum0 is Sum + (I * 10), Average is Sum0 / I, write(Average), nl, I0 is I + 1, moving_average(Sum0, N, I0). moving_average(_, N, I):- I == N. main:- moving_average(10), halt.
$ gplc prolog/ch-1.p $ prolog/ch-1 10.0 15.0 20.0 25.0 30.0 35.0 40.0 45.0 50.0
Typically when one thinks of a stream the idea is of a virtually endless source of data.
Or, at least, data which is handled as if this were the case. Here the "stream" is
simulated by a generated sequence of numbers. For each recursive call to
moving_average/3 we increase the simulated "stream" by 10 and compute the moving
(The idea of a stream in Prolog is fairly specific. My preferred Prolog is Gnu Prolog, which has a very nice write up of the subject.)
You are given a score $S. You can win basketball points e.g. 1 point, 2 points and 3 points. Write a script to find out the different ways you can score $S.
:-initialization(main). points --> . points --> point, points. point --> ; ; ; . basketball_points(Points, Goal):- length(Points, Goal), phrase(points, Points), sum_list(Points, Goal). zero_remove(, ). zero_remove([H|T], [ZR_H|ZR_T]):- delete(H, 0, ZR_H), zero_remove(T, ZR_T). main:- findall(Ps, basketball_points(Ps, 4), Points), zero_remove(Points, PointsZR), sort(PointsZR, PointsZR_Unique), write(PointsZR_Unique), nl, halt.
$ gplc prolog/ch-2.p $ prolog/ch-2 [[1,1,1,1],[1,1,2],[1,2,1],[1,3],[2,1,1],[2,2],[3,1]]
This is almost exactly identical to a solution for Challenge 112. The only difference is that I changed the predicate and variable names to match the current problem statement!