Function that takes a positive integer N
and returns the sum of the bits in the binary representation. For example bits(7)
is 3
and bits(8)
is 1
. Direct and tail-recurive versions.
Calculates perimeter, area and enclosing rectangle for different types shape:
{ circle, { X, Y }, R }
: circle (centre, radius){ rectangle, { X, Y }, W, H }
rectangle (centre, width, height){ triangle, { X1, Y1 }, { X2, Y2 }, { X3, Y3 } }
triangle (P1, P2, P3, coordinates of the three points)
In this first version I stuck to what was taught so far and made sure the arguments given match what’s expected.
In this version I decided to assume that when a tuple starting with rectangle
is given, it matches the expected representation, and it allowed me to simplify the pattern matches. I also discovered that you can put assignments in the pattern matches, which allowed me to re-use matched expressions without re-writing them (e.g. enclose
for a rectangle).
Tests for the shapes function, using pattern matching to check calculated values against the expected ones (poor-person’s unit testing). I had to write a function to compare two floats with a margin for rounding.