Mercurial > repos > other > SevenLanguagesInSevenWeeks
annotate 3-Prolog/day2-maths.pl @ 103:98be775c533c default tip
An odd "non-determinism" example from StackOverflow
It is clever, but doesn't make much sense as to how it gets its results
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sun, 14 Jul 2019 13:44:13 +0100 |
parents | f86bb0d669be |
children |
rev | line source |
---|---|
59
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
1 % First use of variable assignment! |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
2 % We use a mix of rules and facts to do maths on lists. |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
3 count(0, []). |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
4 % This seems backwards, but we're saying "Count of a list with a head and a tail |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
5 % is the count of its tail (which will be assigned to TailCount) plus one, which |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
6 % is then assigned to Count, which gets passed back out" |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
7 count(Count, [Head|Tail]) :- count(TailCount, Tail), Count is TailCount + 1. |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
8 |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
9 sum(0, []). |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
10 sum(Total, [Head|Tail]) :- count(Sum, Tail), Total is Head + Sum. |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
11 |
f86bb0d669be
Add a quick bit of maths code (list counting/summing)
IBBoard <dev@ibboard.co.uk>
parents:
diff
changeset
|
12 average(Average, List) :- sum(Sum, List), count(Count, List), Average is Sum / Count. |