0

so this is my multiplication function:

multiplicacion n 1 = n
multiplicacion n m = n + (multiplicacion n (m - 1)) 

works with integers but when attempting to multiply floats:

*Main> multiplicacion  4.1 4
16.4

that works but if the second argument is also a float, this happens:

*Main> multiplicacion  4 4.1

the function breaks.

brian
  • 47
  • 1
  • 5

2 Answers2

5

To see what's happening, unroll the function execution - i.e. repeatedly replace function call with its body.

Let's consider the first example:

multiplication 4.1 4
= 4.1 + (multiplication 4.1 (4 - 1))
= 4.1 + (4.1 + (multiplicaiton 4.1 (3 - 1))
= 4.1 + (4.1 + (4.1 + (multiplicaiton 4.1 (2 - 1)))
= 4.1 + (4.1 + (4.1 + 4.1)
= 16.4

Now let's look at the second example:

multiplication 4 4.1
= 4 + (multiplication 4 (4.1 - 1))
= 4 + (4 + (multiplication 4 (3.1 - 1)))
= 4 + (4 + (4 + (multiplication 4 (2.1 - 1))))
= 4 + (4 + (4 + (4 + (multiplication 4 (1.1 - 1)))))
= 4 + (4 + (4 + (4 + (4 + (multiplication 4 (0.1 - 1)))))
= 4 + (4 + (4 + (4 + (4 + (4 + (multiplication 4 (-0.9 - 1))))))
= 4 + (4 + (4 + (4 + (4 + (4 + (4 + (multiplication 4 (-1.9 - 1)))))))
= 4 + (4 + (4 + (4 + (4 + (4 + (4 + (4 + (multiplication 4 (-2.9 - 1))))))))
... and so on

The second argument will never be equal to one, and therefore the first definition multiplication n 1 = n will never match, and therefore the function will forever call itself.

Your function can only multiply by positive integer numbers. Giving it a fractional number results in an infinite loop.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
5

The problem is that you're decrementing m by 1 every call. So let's look what happens with mult 4 4.1, expanding each line:

mult 4 4.1
4 + (mult 4 3.1)
4 + (4 + (mult 4 2.1))
4 + (4 + (4 + (mult 4 1.1)))
4 + (4 + (4 + (4 + (mult 4 0.1)))))
4 + (4 + (4 + (4 + (4 + (mult 4 (-0.9)))))))
...

based on this expansion, can you see what's going wrong here? Because at no stage does m actually equal 1, you never hit the base case.

A. R.
  • 2,031
  • 13
  • 27