Mercurial > repos > other > SevenLanguagesInSevenWeeks
changeset 59:f86bb0d669be
Add a quick bit of maths code (list counting/summing)
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Wed, 27 Sep 2017 20:19:01 +0100 |
parents | 90c4b7f28690 |
children | 643eec1f9e3a |
files | 3-Prolog/day2-maths.pl |
diffstat | 1 files changed, 12 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/3-Prolog/day2-maths.pl Wed Sep 27 20:19:01 2017 +0100 @@ -0,0 +1,12 @@ +% First use of variable assignment! +% We use a mix of rules and facts to do maths on lists. +count(0, []). +% This seems backwards, but we're saying "Count of a list with a head and a tail +% is the count of its tail (which will be assigned to TailCount) plus one, which +% is then assigned to Count, which gets passed back out" +count(Count, [Head|Tail]) :- count(TailCount, Tail), Count is TailCount + 1. + +sum(0, []). +sum(Total, [Head|Tail]) :- count(Sum, Tail), Total is Head + Sum. + +average(Average, List) :- sum(Sum, List), count(Count, List), Average is Sum / Count. \ No newline at end of file