Okay, let's do this without using sum or eval then 🙃
sum
eval
module Calculator DivisionByZero = Class.new(RuntimeError) module_function def add(x,y) = y.abs.times. reduce(x) {|acc,_| y > 0 ? acc.next : acc.pred } def sub(x,y) = y.abs.times. reduce(x) {|acc,_| y > 0 ? acc.pred : acc.next } def mult(x,y) = y.abs.times. reduce(0) {|acc,_| add(acc,x)}. then {|num| y < 0 ? invert(num) : num } def div(x,y) raise DivisionByZero if y.zero? divisor = y.abs val = x.abs times = 0 while sub(val,divisor) >= 0 val = sub(val,divisor) times = times.next end times = x >= 0 ? times : invert(times) y >= 0 ? times : invert(times) end def invert(x) = x > 0 ? sub(0,x) : x.abs end require 'rspec' RSpec.describe(Calculator) do specify { expect(Calculator.add(5,6)).to eq(11) } specify { expect(Calculator.add(5,0)).to eq(5) } specify { expect(Calculator.add(0,5)).to eq(5) } specify { expect(Calculator.add(-5,5)).to eq(0) } specify { expect(Calculator.sub(5,6)).to eq(-1) } specify { expect(Calculator.sub(5,1)).to eq(4) } specify { expect(Calculator.sub(0,1)).to eq(-1) } specify { expect(Calculator.sub(-5,2)).to eq(-7) } specify { expect(Calculator.sub(-5,-2)).to eq(-3) } specify { expect(Calculator.sub(5,-2)).to eq(7) } specify { expect(Calculator.mult(2,3)).to eq(6) } specify { expect(Calculator.mult(2,0)).to eq(0) } specify { expect(Calculator.mult(0,10)).to eq(0) } specify { expect(Calculator.mult(0,-10)).to eq(0) } specify { expect(Calculator.mult(1,-10)).to eq(-10) } specify { expect(Calculator.mult(-1,-10)).to eq(10) } specify { expect(Calculator.div(6,2)).to eq(3) } specify { expect(Calculator.div(6,6)).to eq(1) } specify { expect(Calculator.div(7,3)).to eq(2) } specify { expect(Calculator.div(-6,3)).to eq(-2) } specify { expect(Calculator.div(0,3)).to eq(0) } specify { expect(Calculator.div(6,-5)).to eq(-1) } specify { expect{ Calculator.div(6,0) }.to raise_error(Calculator::DivisionByZero) } end
I'm kind of not happy with div, but hard to do it nicely without introducing fractions.
div
cc @ben
Woah this is really nice!
Nice stuff!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Okay, let's do this without using
sum
oreval
then 🙃I'm kind of not happy with
div
, but hard to do it nicely without introducing fractions.cc @ben
Woah this is really nice!
Nice stuff!