Instructions
Create a function compose that takes two procs (f and g) and
returns a new proc that applies g first, then f.
Mathematical composition: (f ∘ g)(x) = f(g(x))
Example:
```ruby
add_one = ->(x) { x + 1 }
double = ->(x) { x * 2 }
composed = compose(add_one, double)
composed.call(3) # double(3) = 6, add_one(6) = 7
=> 7
Hints:
- Return a new proc/lambda
- Inside, call g first, then f
- ->(x) { f.call(g.call(x)) }
Your Code
def compose(f, g)
->(x) { f.call(g.call(x)) }
end
RSpec.describe "compose" do
let(:add_one) { ->(x) { x + 1 } }
let(:double) { ->(x) { x * 2 } }
let(:square) { ->(x) { x * x } }
it "composes two functions" do
composed = compose(add_one, double)
expect(composed.call(3)).to eq(7) # double(3)=6, +1=7
end
it "order matters" do
f_then_g = compose(double, add_one)
g_then_f = compose(add_one, double)
expect(f_then_g.call(3)).to eq(8) # (3+1)*2
expect(g_then_f.call(3)).to eq(7) # 3*2+1
end
it "works with multiple compositions" do
triple = compose(compose(add_one, double), square)
expect(triple.call(2)).to eq(9) # 2²=4, *2=8, +1=9
end
end
Results
Click "Run Tests" to see results