Last active
June 30, 2021 20:41
-
-
Save JoelQ/c472b7b0b42afb39db00caf71b58af92 to your computer and use it in GitHub Desktop.
Derive addition, multiplication, and exponentiation from from `Integer#next`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add(number1, number2) | |
number2.times.reduce(number1) { |total| total.next } | |
end | |
add(2,3) | |
# => 5 | |
def subtract(number1, number2) | |
number2.times.reduce(number1) { |total| total.pred } | |
end | |
subtract(5, 3) | |
# => 2 | |
def multiply(number1, number2) | |
number1.times.reduce(0) { |total| add(total, number2) } | |
end | |
multiply(2, 3) | |
# => 6 | |
def exponent(base, power) | |
power.times.reduce(1) { |total| multiply(total, base) } | |
end | |
exponent(2, 3) | |
#=> 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://gist.github.com/JoelQ/b5356aaa80e2e032c6cabfe79d5d0da5