Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Last active Jun 30, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@JoelQ JoelQ commented Jun 30, 2021

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