This repo accompanies the article “Representations count”.
It contains a challenge: how would you add support for negative numbers on a (hypothetical) computer which only has natural numbers built in?
In practice, that means implementing the constructor, factory methods and
instance methods of the SignedNumber
class. That
class includes a refinement which discourages you
from accidentally using negative numbers.
git clone https://github.com/tomstuart/negative-numbers.git
cd negative-numbers
bundle install
bundle exec rspec
- Edit
lib/signed_number.rb
to make the next failing test pass - If more failing tests remain, go to 4
- Celebrate! 🎉
One way to solve this challenge is to represent a signed number as the
combination of a “sign” (positive or negative) and a “size” (absolute
magnitude). See the sign-and-size
branch
for a worked solution.
An alternative is to represent a signed number as the difference between two natural numbers.
See the left-and-right
branch
for a worked solution.
The first representation is easier to understand, but the second is arguably easier to implement correctly.