title: SML: Implementing Multiply with Restrictions
body: <p>I'm trying to implement multiply in SML with a few restrictions.  I'm given the following <code>add</code> function:</p>
  
  <pre><code>fun add (0 : int, m : int) : int = m
      | add (n : int, m : int) : int = 1 + add(n-1, m)
  </code></pre>
  
  <p>I'm trying to write a function such that <code>mult (m, n)</code> recursively calculates the product of m and n, for any two natural numbers <code>m</code> and <code>n</code>. Your implementation may use the function <code>add</code> mentioned above and <code>-</code> (subtraction), but it may not use <code>+</code> or <code>*</code>.</p>
  
  <p>Here's my attempt:</p>
  
  <pre><code>fun multiply(0 : int, m : int) = 0
      | multiply(n : int, 0 : int) = 0
      | multiply(1 : int, m : int) = m
      | multiply(n : int, 1 : int) = n
      | multiply(~1 : int, m : int) = ~m
      | multiply(n : int, ~1 : int) = ~n
      | multiply(n : int, m : int) =
          if (n &gt; 0 andalso m &gt; 0) then
              add(add(0, n), multiply(n, m - 1))
          else
              if (n &lt; 0 andalso m &lt; 0) then
                  multiply(~n, ~m)
              else
                  if (n &lt; 0 andalso m &gt; 0) then
                      n - multiply(n, m - 1)
                  (* n &gt; 0 and m &lt; 0 *)
                  else
                      m - multiply(m, n - 1);
  </code></pre>
  
  <p>It works when <code>n</code> and <code>m</code> are both positive or both negative but not when one is positive and the other negative but I can't seem to figure out my bug.  For instance,</p>
  
  <p><code>multiply(3, ~10)</code> evaluates to <code>0</code>.  So I think my recursive call is getting to <code>0</code> and causing it to evaluate to <code>0</code>.  Having said that, my base cases take care of this so I'm not sure how it'd be possible.</p>
  
  <p>Ideas?</p>