Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to write efficient functional code, then it is a good idea to avoid using the <code>@</code> operator, because concatentation of lists is very inefficient. </p> <p>Here is an example of how you can write a function to generate all combinations:</p> <pre><code>let rec combinations acc size set = seq { match size, set with | n, x::xs -&gt; if n &gt; 0 then yield! combinations (x::acc) (n - 1) xs if n &gt;= 0 then yield! combinations acc n xs | 0, [] -&gt; yield acc | _, [] -&gt; () } combinations [] 3 [1 .. 4] </code></pre> <p>The parameters of the function are:</p> <ul> <li><code>acc</code> is used to remember elements that are already selected to be included in the combination (initially this is an empty list)</li> <li><code>size</code> is the remaining number of elements that we need to add to <code>acc</code> (initially this is the required size of the combinations)</li> <li><code>set</code> is the set elements to choose from</li> </ul> <p>The function is implemented using a simple recursion. If we need to generate combinations of size <code>n</code> then we can either add or don't add the current element, so we try to generate combinations using both options (first case) and add all of them to the generated sequence using <code>yield!</code>. If we need 0 more elements, then we successfuly generated a combination (second case) and if we end with some other number but don't have any remaining elements to use then we cannot return anything (last case).</p> <p>Combinations with repetition would be similar - the difference is that you don't need to remove the elements from the list (by using just <code>xs</code> in the recursive calls) so there are more options of what to do.</p>
 

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