# Need help with this

This is a homework question and I’m really confused by it:

the method exp(x,y) is passed two integers and returns x^Y write a
recursive version of exp(s,y) in Ruby.

this is what I have:

def exp(x,y)

if y = 1
return x

return x * exp(x, y-1)

is this correct?

On May 31, 2012, at 17:50 , Spencer P. wrote:

return x

return x * exp(x, y-1)

is this correct?

yourself.

Given the function:

def assert_equal expected_value, actual_value

you can write the following form:

assert_equal z, exp(x, y)

What triplets of [x, y, z] would you need to verify that your function
is working correctly? Once you figure out what tests you need, knowing
if your code is working is pretty much automatic. Put this in a file
“test_exp.rb” and try it out:

require “exp”
require “minitest/autorun”

class TestHomework < MiniTest::Unit::TestCase
def test_exp
# … fill in the blanks …
end

def test_exp_negative_cases
# … fill in the blanks …
end

# … etc …

end

Once all the tests are running, you might want to ask yourself how many
different ways your function can be implemented. You can then modify as
you see fit and you’ll always have your tests to verify that your
modifications are still working.

No, this code will not run.

The main problem with the code is that you are missing some `end`
statements. You should close functions and control flow statements with
`end`. So your code would be.

``````def exp(x,y)
if y = 1
return x
end
return x * exp(x, y-1)
end
``````

Another problem though is the misuse of `=` in place of `==`. While in
normal mathematics `=` does test for equality, this is not the case in
programming. Since `=` is reserved for variables, we use `==` to test
for equality.

``````def exp(x,y)
if y == 1
return x
end
return x * exp(x, y-1)
end
``````

But a better way to write that code would be to use the shortcut-if
statement. You can put an if-statement following some code to only run
that line. So instead of writing this.

``````if y == 1
return x
end
``````

You could write this.

``````return x if y == 1
``````

This makes the code both easier to read and makes your intent clearer.
So in the end, we have revised your method to this.

``````def exp(x,y)
return x if y == 1
return x * exp(x, y-1)
end
``````

Bryan D.

On Fri, Jun 1, 2012 at 2:50 AM, Spencer P. [email protected] wrote:

return x

return x * exp(x, y-1)

is this correct?

No, you are missing an “end”. You could also include treatment for y == 0. (Hint: a case block might help.)

Kind regards

robert