Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need a function of two lists; the second list provides indices for the first list. There are two possibilities: the second list is sorted in ascending order, or the second list is not sorted in any way. If the second list is sorted, your function will be a lot more efficient. This is so because a list can be traversed efficiently from left to right, but random access to an element with a given index is not quick.</p> <p>In any case, a tail-recursive solution is possible. (I have a suspicion that this is a homework question...)</p> <p>The idea is not to use any temporary variables, but to build the result as you go through the lists. Think about your problem in terms of mathematical induction. What is the base of induction? Empty list of indices gives empty result. What is the step of induction? Take the next given index from the second list, appending one element from the first list to the result, and assume (by induction) that all other indices will be handled correctly.</p> <p>Here is what you can do in case the second list is sorted in ascending order, with no repeated elements. <code>indices_tr</code> is a tail-recursive function that has four arguments; <code>result</code> is the previously accumulated resulting list, <code>xs</code> is the remaining part of the first list, <code>n</code> is the current index in that list, and <code>is</code> is the remaining part of the list of indices.</p> <pre><code>let indices xs is = let rec indices_tr result (x::xs) n = function | [] -&gt; result | i::is when i==n -&gt; indices_tr (x::result) xs (n+1) is | is -&gt; indices_tr result xs (n+1) is in indices_tr [] xs 0 is ;; </code></pre> <p>There is a warning that the empty list is not handled.</p> <p>The result is a list in reverse order:</p> <pre><code> # indices [1;3;5;7] [0;1;2];; - : int list = [5; 3; 1] </code></pre> <p>You cannot do much better with a pure tail-recursive solution; you could of course apply List.rev to that.</p>
    singulars
    1. This table or related slice is empty.
    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. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    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