Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As you mention, it would be a nested/double loop in any imperative programming language. What you are actually missing is the second loop.</p> <p>Your "inner" loop goes through all elements of <code>d</code>, and when this is done, your "outer" loop tries to pop the top element of <code>m</code> and start all over, as seen from this line of your code:</p> <pre><code>else if null d then number_in_months(d, tl m) </code></pre> <p>However as you can see, you have just tested the list <code>d</code> to be empty and you supply this (exact same list) to your recursive call on the tail of <code>m</code>, which will then fall in this same case for each successive call until <code>m</code> is also empty and you return 0.</p> <p>Thus what you are missing is to "keep a copy" of the original input list <code>m</code>. This can be done in various ways, but an inner (helper) function is properly the most used one and it even "looks" like a nested loop</p> <pre><code>fun number_in_months (d, m) = let fun nim' ([], y::ys) = nim (d, ys) (* 1 *) | nim' (_, []) = 0 (* 2 *) | nim' ((_, x2, _) :: xs, yss as (y::ys)) = ... (* 3 *) in nim'(d, m) end </code></pre> <p>Using pattern matching the above code gets much simpler and less error prone. In case 1, the "inner" loop has gone through all elements in <code>d</code>, thus the recursive call using <code>d</code> from the outer function which is not changed at any time. In case 2, the "outer" loop has gone through all elements of <code>m</code> and we return 0 (the neutral element of addition). In case 3 we do the actual work. Here pattern matching is used such that we don't need to enforce the type of the argument and we don't need to pull out the 2nd element of the triple, we already have it in the variable <code>x2</code>. All that is needed is to do the computation and make a recursive call with <code>xs</code> and <code>yss</code>.</p> <p>When doing it this way, the inner (helper) function is using a "copy" of the original input list <code>d</code> and stepping through its elements (potentially modifying it), but we always got a reference to the original input list, which we can use if/when needed.</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