Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Last active June 30, 2021 20:41
Show Gist options
  • Save JoelQ/c472b7b0b42afb39db00caf71b58af92 to your computer and use it in GitHub Desktop.
Save JoelQ/c472b7b0b42afb39db00caf71b58af92 to your computer and use it in GitHub Desktop.
Derive addition, multiplication, and exponentiation from from `Integer#next`
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
@JoelQ
Copy link
Author

JoelQ commented Jun 30, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment