Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think there are a couple of things going on here.</p> <p>First, I think what you're trying to do with the fact function (use a function with a default value as though its type actually had one fewer parameters) is not possible. An (Int,Int) => Int is still an (Int,Int) => Int even if the second Int defaults to 1. You can't pass it as an Int => Int. I can see where you might think you could, though.</p> <p>Second, your fact and factorial functions are not equivalent. The factorial function uses the original value of 'a' over and over no matter how many times you recurse. The fact function, uses a decrementing 'a' in each call.</p> <p>Based on your 'fixed' factorial function, the function effectively takes three parameters: the original a, the decrementing n, and the multiplying prev. The below code is equivalent. </p> <pre><code>def sum(f: (Int,Int,Int) =&gt; Int, a: Int, b: Int): Int = if (a &gt; b) 0 else f(a,a,1) + sum(f, a+1, b) def fact(a: Int, n: Int, prev:Int): Int = if (n == 0) prev else fact(a, n-1, a * prev) def sumFactorials(a: Int, b: Int): Int = sum(fact, a, b) </code></pre> <p>You also can't write sum as:</p> <pre><code>def sum(f: (Int, Int) =&gt; Int, a: Int, b: Int): Int = if (a &gt; b) 0 else f(a) + sum(f, a+1, b) </code></pre> <p>The passed in function f might have a default parameter and it might not, so it wouldn't be safe for the compiler to allow the f(a) call.</p> <p>I think default parameters are implemented more like "syntactic sugar", as they say, attached to the actual function rather than like function currying. You can do this with currying, but you have to explicitly declare the curried function. Assuming that you want to use the logic from fact (and not factorial), you can do it like so:</p> <pre><code>def sum(f: Int =&gt; Int, a: Int, b: Int): Int = if (a &gt; b) 0 else f(a) + sum(f, a+1, b) def fact(prev:Int = 1)(a: Int): Int = if (a == 0) prev else fact(a * prev)(a-1) def sumFactorials(a: Int, b: Int): Int = sum(fact(1), a, b) </code></pre> <p>Note that we had to switch the position of fact's parameters.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload