Note that there are some explanatory texts on larger screens.

plurals
  1. POF# return element pairs in list
    text
    copied!<p>I have been looking for an elegant way to write a function that takes a list of elements and returns a list of tuples with all the possible pairs of distinct elements, not taking into account order, i.e. (a,b) and (b,a) should be considered the same and only one of them be returned. I am sure this is a pretty standard algorithm, and it's probably an example from the cover page of the F# documentation, but I can't find it, not even searching the Internet for SML or Caml. What I have come up with is the following:</p> <pre><code>let test = [1;2;3;4;5;6] let rec pairs l = seq { match l with | h::t -&gt; yield! t |&gt; Seq.map (fun elem -&gt; (h, elem)) yield! t |&gt; pairs | _ -&gt; () } test |&gt; pairs |&gt; Seq.toList |&gt; printfn "%A" </code></pre> <p>This works and returns the expected result <em>[(1, 2); (1, 3); (1, 4); (1, 5); (1, 6); (2, 3); (2, 4); (2, 5); (2, 6); (3, 4); (3, 5); (3, 6); (4, 5); (4, 6); (5, 6)]</em> but it looks horribly unidiomatic. I should not need to go through the sequence expression and then convert back into a list, there must be an equivalent solution only involving basic list operations or library calls...</p> <p><em>Edited:</em></p> <p>I also have this one here</p> <pre><code>let test = [1;2;3;4;5;6] let rec pairs2 l = let rec p h t = match t with | hx::tx -&gt; (h, hx)::p h tx | _ -&gt; [] match l with | h::t -&gt; p h t @ pairs2 t | _ -&gt; [] test |&gt; pairs2 |&gt; Seq.toList |&gt; printfn "%A" </code></pre> <p>Also working, but like the first one it seems unnecessarily involved and complicated, given the rather easy problem. I guess my question is mor about style, really, and if someone can come up with a two-liner for this.</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